How to make a counter in a for loop?

조회 수: 57 (최근 30일)
Betty
Betty 2017년 12월 28일
답변: Akira Agata 2018년 1월 30일
Hi.
I have a 330x7 matrix, and want to access every 10th row from 1:7.
My code looks like this, but I get error whatever I try.
patient = 33;
k = 10;
for i = 1:patient
joint7(i,:) = main(10,1:7+k);
k = k+10;
end
What am I doing wrong?

답변 (2개)

Akira Agata
Akira Agata 2018년 1월 30일
You can extract every 10th row of the matrix much easier, like:
% Assuming your 330x7 matrix
main = rand(330,7);
% Extract every 10th row
joint7 = main(10:10:end,:);

umichguy84
umichguy84 2018년 1월 30일
When using a for loop you don't have to step by 1, you can step by any number.
So while this would fix your issue:
patient = 33;
k = 10;
for i = 1:patient
joint7(i,:) = main(k*i,1:7);
end
An alternative is:
patient = 33;
k=10;
joint7 = nan(patient,7); % It's faster if you prepopulate
i=1;
for k = 10:k:length(main)
joint7(i,:) = main(k,1:7);
i = i + 1;
end
Either will work, but I wanted to provide an alternative way of doing it.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by