How to extract rows from matrix in a for loop?

2 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by