Looping with indices that are not equally spaced
9 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
John F
le 23 Juin 2011
Commenté : Walter Roberson
le 22 Déc 2019
I'm trying to run a loop on a group of indices I obtained using "find". The indices will not always be consecutive. So, running a for loop like:
won't work. I'm trying to avoid doing something like:
for i = 1:length(VECTOR)
Any ideas?
2 commentaires
Oleg Komarov
le 23 Juin 2011
not clear why it won't work. Depends how you structure the operations inside the loop. Post more code.
Daniel Shub
le 23 Juin 2011
What do you mean it doesn't work? What would you expect to get with:
indices = [1,2,3,5,7,13,11];
for i = indices, i, end
Réponse acceptée
Laura Proctor
le 23 Juin 2011
Actually, it will work.
for idx = [ 1 -2 10 12.5 0 ]
disp(idx)
end
Isn't MATLAB cool?
0 commentaires
Plus de réponses (2)
John F
le 23 Juin 2011
2 commentaires
Laura Proctor
le 23 Juin 2011
Modifié(e) : Walter Roberson
le 22 Déc 2019
You are correct - check out Loren's Blog, it explains this behavior much better than I can:
Daniel Shub
le 23 Juin 2011
Modifié(e) : Walter Roberson
le 22 Déc 2019
Yeah, but check out what it does do with a column. You should have a read of:
Frederick Abangba Akendola
le 22 Déc 2019
Please, how do I write a “For” loop with irregular interval? For example; 2,4,8,16,32
1 commentaire
Walter Roberson
le 22 Déc 2019
for K = 2.^(1:5)
result = whatever involving K
end
However, most of the time you want to create one output per input. The general way to do that is
K_vals = 2.^(1:5);
numK = numel(K_vals);
results = zeros(size(K_vals));
for K_idx = 1 : numK
K = K_vals(K_idx);
results(K_id) = whatever involving K
end
plot(K_vals, results)
Voir également
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!