221b
221b

Reputation: 431

Print/Store each row in matrix - MATLAB

I have a 150 X 4 matrix and I wish to loop through the matrix length and print each of the rows out.

This is my attempted code:

X = xlsread('filename.csv');

J = X(:, [2:5]) % extracting rows 2 to 5 into a matrix

for i= 0:length(J)
Y = J(i,:); %loop through each row and store it in Y
end;

But I keep getting the following error:

Subscript indices must either be real positive integers or logicals.

Is my approach incorrect? What am I missing out here? I simply want to loop through each row and store it in a variable.

Upvotes: 0

Views: 185

Answers (1)

Miriam Farber
Miriam Farber

Reputation: 19634

In MATLAB the indices start at 1 and not at 0, so you should do:

for i= 1:length(J)
    Y = J(i,:); %loop through each row and store it in Y
end;

In addition, regarding the following line that you wrote:

J = X(:, [2:5]) % extracting rows 2 to 5 into a matrix

Note that you actually stored in J columns 2,3,4,5, of X and not rows 2,3,4,5.

Upvotes: 1

Related Questions