add-semi-colons
add-semi-colons

Reputation: 18800

How do I append elements to a matrix using a for loop?

I have following data matrix, I want to iterate over this matrix and look at a value in the last column based on a given row and add that row - last element of that row to a new matrix.

5.1000    3.3000    1.7000    0.5000    1.0000
6.8000    3.2000    5.9000    2.3000    3.0000
5.0000    2.3000    3.3000    1.0000    2.0000
7.4000    2.8000    6.1000    1.9000    3.0000
6.5000    3.2000    5.1000    2.0000    3.0000
4.8000    3.4000    1.9000    0.2000    1.0000
4.9000    3.0000    1.4000    0.2000    1.0000
5.1000    3.8000    1.5000    0.3000    1.0000
5.1000    3.4000    1.5000    0.2000    1.0000
5.5000    2.6000    4.4000    1.2000    2.0000

This is the code that I have

 M1 = [];
 M2 = [];
 M3 = [];
    for i=1:length(currentCell)
        if currentCell(1,5) == 1.00
            m3Data = currentCell(1:1,1:4);
            %how can I add m3Data to M1
        end
    end

Upvotes: 1

Views: 383

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78316

Let your original matrix be M, then this

M1 = M(find(M(:,5)==1),1:4)

puts all the rows ending with a 1 into M1, excluding the final column. Is that what you want ?

You could do it with a for loop if you want, but I don't see any need.

Upvotes: 1

Related Questions