如何迭代数组并获取数组中每行的行元素 - Matlab

时间:2014-11-14 01:35:27

标签: arrays matlab

我需要帮助使用for循环将数组中的行元素分配给新变量。 e.g。

y = magic(2)

for i = size(y,1)
    m = y(i,:)
    % do some calculations to row vector 'm' and then iterate to next row vector and      replace previous 'm' with new 'm' and perform same calculations
end

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

看起来你的问题是for循环,你错过了迭代器i的初始值:

y = magic(2)
for i = 1:size(y,1)
    m = y(i,:)
    % use m
end

答案 1 :(得分:0)

更直接:for自动沿着矩阵的进行迭代;所以你可以使用:

y = magic(2);
for row = y.' %'// transpose y, and iterate through the columns of that
    %// 'row' contains each row of y, but as a column vector. Transpose if needed
end