Azzera filtri
Azzera filtri

How to make a counter in a for loop?

26 visualizzazioni (ultimi 30 giorni)
Betty
Betty il 28 Dic 2017
Risposto: Akira Agata il 30 Gen 2018
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?

Risposte (2)

Akira Agata
Akira Agata il 30 Gen 2018
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 il 30 Gen 2018
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.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by