How to extract rows from matrix in a for loop?

I have a n x m -matrix and want extract each line of the matrix in a for-loop. In each step one row should be extracted, in the next step the next row and so on ...
I tried:
a = [ 1 2 3 4; 4 5 6 4; 1 1 1 1; 6 3 5 7];
lines = @(x) size(x,1); % lines(x) calculates number of lines in matrix x
for i = 1 : lines(a);
profrow = a(i,:);
t = profrow(i);
end
r = [t]
I want that the vector profrow(i) contains always one line of the matrix. But in the end it only contains one element (The element a(i,i)). Anybody know why and/or can help me how to do what I want? Thx.

 Accepted Answer

Within the loop, profrow does contain the ith row as you indeed want. Your code is correct. t is then the ith element of that row, so indeed t does contain a(i,i), but profrow is exactly what you ask.
After the loop, profrow is only the last row.

3 Comments

Thanks, for your answer. That was what I want to know!
By the way, can you explain to my why
for i = 1 : lines(a);
profrow(i) = a(i,:);
end
does not work? I thought this would be the correct code because (1) profrow is a function of i and (2) this is the usual way I saw for loops.
Since i is scalar (just one number), profrow(i) is a single element of the matrix/vector profrow. If you try to assign to that single element several elements (as in a(i, :)|) then matlab is rightfully going to complain.
You could make profrow a cell array, each element of a cell array can store anything you want: nothing, single numbers, whole row of numbers, whole matrices, etc:
profrow = cell(size(a, 1), 1);
for row = 1 : size(a, 1)
profrow{row} = a(row, :); %note the different brackets
end
%note that the entire code above could be simple replaced by:
profrow = num2cell(a, 2);
There's not much point in the above though, you can just keep a around, and simply index it when needed: a(row, :).
thx! Totally helpfull for me!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 8 Sep 2016

Commented:

on 9 Sep 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!