How to extract rows from matrix in a for loop?
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
Guillaume
le 8 Sep 2016
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 commentaires
Guillaume
le 9 Sep 2016
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, :).
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!