How do a create a list of indexes based on the value and a new array from that? MATLAB

Viewed 50

I would like to eliminate all the columns in which the third row contain zero values in my dataset.

As an example:

original_data = [1 2 3 4 5; 1 2 3 4 5; 0 0 0 1 2] 

For the first three columns (with zeros on third line), I would like to create a new array in which the colums with zeros in third line are deleted to get the result:

new_data = [ 4 5;  4 5; 1 2] 

I would also like an array of the column indices of the non-zero values in the original array.

For example:

original_indices = [4, 5]

I tried:

dados_teste = dados_out_15;
dados_p6 = [];
[m,n] = size(dados_teste)
for i = 1:n
    
    if dados_teste(3:i) == 0;
        dados_p6 = dados_teste(:,i)
    else
        dados_p6 = dados_teste(:,n)
    end
end

But it clearly does not work...

1 Answers

I would apply the find() function to find all the non-zero indices, then apply matrix indexing to generate a new array that only contains the columns corresponding to the non-zero indices in the third row.

Sample_Array = [20 30 40 50; 30 20 70 90; 0 2 1 2];

%Grabbing the third row of the matrix%
Third_Row = Sample_Array(3,:);

%Finding all the non-zero indices%
[Non_Zero_Indices] = find(Third_Row);

%Using matrix indices to generate a new array based on the non-zero
%indicies%
New_Matrix = Sample_Array(:,Non_Zero_Indices);

%Printing matrices% 
Sample_Array

New_Matrix

Non_Zero_Indices
Related