How to extract rows from matrix in a for loop?

조회 수: 4 (최근 30일)
HolgSpre
HolgSpre 2016년 9월 8일
댓글: HolgSpre 2016년 9월 9일
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.

채택된 답변

Guillaume
Guillaume 2016년 9월 8일
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
Guillaume
Guillaume 2016년 9월 9일
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, :).
HolgSpre
HolgSpre 2016년 9월 9일
thx! Totally helpfull for me!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by