Alexander
Alexander

Reputation: 420

Append rows in matrix

for i = 1:6
    if data(i,1) == 1
        disp(i)
        m(i,:) = data(i,:)
    end
end

The code above returns a matrix m, with rows of data from the data file.

However, data(i,1) == 1 is true 4 times for the particular data, however m has 6 rows. 2 of the rows of m are just full of 0's, but the if statement is only true 4 times.

Why is that happening?

Upvotes: 1

Views: 1570

Answers (2)

Wolfie
Wolfie

Reputation: 30165

In answer to "why is that happening", it is because your matrices are the same size, but you only assign values to the rows which satisfy a condition. Therefore leaving other rows as 0s.

You either need a way to build m row by row (see end of this post) or create it in another way (my answer).


You can do this with logical indexing

% For creating m
m = data(data(:, 1) == 1, :);

% For displaying which indices satisfy your condition, one call to disp
disp( find(data(:, 1) == 1) )

Breaking this down, m is assigned to the values of data, where the column 1 of data is equal to 1, and all of the columns.

find returns the index of any non-zero element. The logical indexing returns an array of 0s and 1s, so all elements which satisfy the condition (and are 1) will be indexed by find.

You could also create the logical index and use it twice, better for maintenance at a later date if your condition changes:

% create logical index
idx = ( data(:,1) == 1 );

% same as above but using idx
m = data(idx, :);
disp( find(idx) )

Documentation

Logical indexing - https://uk.mathworks.com/help/matlab/matlab_prog/find-array-elements-that-meet-a-condition.html

find - https://uk.mathworks.com/help/matlab/ref/find.html


@Ander's suggestion to append only certain rows will work, and demonstrates well how to build a matrix. However, in this case you do not need your loop and if condition at all.

Upvotes: 4

Ander Biguri
Ander Biguri

Reputation: 35525

This is standard MATLAB.

Lets assume data(1,1) and data(3,1) are 1.

Then m(1,:)=data(1,:) and later m(3,:)=data(3,:). But what about m(2,:) It has to exist, because you filled m(3,:). There is no 3 without 2!

If you want m to have only the ones where data(i,1) == 1 then do:

m=[]; %create empty matrix
for i = 1:6
    if data(i,1) == 1
        disp(i)
        m= [m; data(i,:)]; % "append" to m
    end
end

Upvotes: 3

Related Questions