Extracting every row from a matrix using a for loop

I'm working with some velocity data and have a matrix 23,999x31.
I'm new to using Matlab, I'm able of extracting one row but would now like to be able to create a for loop that will allow me to extract each of the 23,999 rows in the matrix.
Any help for a Matlab novice would be greatly appreciated!

답변 (1개)

Rik
Rik 2021년 10월 15일
This might not be optimal, depending on what you want to do, but the size function is here to help:
data=rand(23999,31)
for row=1:size(data,1)
rowdata=data(row,:);
%do something with that row here
end

댓글 수: 4

Hi, thanks for your response.
Are you aware of a format whereby I can write a loop that takes the data from every row of the 23,999 matrix? So starting with row 1 and extracting all the data in that row and then repeating the process for every row in the matrix, for all 23,999 rows?
Yes, that is what this code does. You can see for yourself. I would recommend trying this with a small example:
data=(1:5).'+rand(5,2);% row x will have values x.####
for row=1:size(data,1)
rowdata=data(row,:);
fprintf('row %d contains:\n',row)
disp(rowdata)
end
row 1 contains:
1.7313 1.7239
row 2 contains:
2.4683 2.1095
row 3 contains:
3.4510 3.8145
row 4 contains:
4.9342 4.5450
row 5 contains:
5.1155 5.7236
See?
If you want to use the entire matrix at once, there is no need to index it at all. If what I showed isn't what you want, please given an example of what it is you want.
Understood, thanks. I've been approaching the problem in the wrong way. I want to be able to determine the mean from each of the 23,999 rows. Can you help with this?
You can do that with the code I already posted:
data=(1:5).'+rand(5,2);% row x will have values x.####
for row=1:size(data,1)
rowdata=data(row,:);
mean(rowdata) %you can store this in a vector
end
ans = 1.1014
ans = 2.4187
ans = 3.5720
ans = 4.6323
ans = 5.6558
But it is better to use mean on the entire array:
mean(data,2) % specify the dimension to make it operate on the rows
ans = 5×1
1.1014 2.4187 3.5720 4.6323 5.6558

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2019a

태그

질문:

2021년 10월 15일

댓글:

Rik
2021년 10월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by