Effacer les filtres
Effacer les filtres

How to make a counter in a for loop?

26 vues (au cours des 30 derniers jours)
Betty
Betty le 28 Déc 2017
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?

Réponses (2)

Akira Agata
Akira Agata le 30 Jan 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 le 30 Jan 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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by