daniel3412
daniel3412

Reputation: 327

How to iterate through array and get row elements for each row in array - Matlab

I need help assigning row elements in an array to a new variable using a for loop. 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

Thanks in advance for your help.

Upvotes: 0

Views: 883

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112769

A little more direct: for automatically iterates along columns of a matrix; so you can use:

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

Upvotes: 0

Javi
Javi

Reputation: 3620

It looks that your problem is the for loop, you are missing the initial value for the iterator i:

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

Upvotes: 2

Related Questions