Nested loop error and saving result

1 vue (au cours des 30 derniers jours)
klb
klb le 2 Juil 2020
Commenté : klb le 2 Juil 2020
Getitng an " Index in position 1 is invalid. Array indices must be positive integers or logical values." error. What am I not doing right in this loop?
i = 0
results = [];
quantity=35;
for p = 1:quantity-2
totalp = 0.23.*p + 4.0
for q = p+1: quantity - 1
totalq = 0.91.*q + 1.3
for r = q+1: quantity
totalr = 0.30.*r + 3.3
total = totalp + totalq + totalr;
results(i,:) = [p,q,r,total]; %error is here: " Index in position 1 is invalid. Array indices must be positive integers or logical values."
i = i +1;
end
end
end
results
I am working with matrices only for my work. Thanks for your time in advance.

Réponse acceptée

Walter Roberson
Walter Roberson le 2 Juil 2020
You start i = 0. You do not increment i until after you store a value. So the first time through, you are storing into results(0,:) . Which is not a valid location. Indices in MATLAB must start at 1.
You should move the
i = i +1;
to just before the assignment.
  1 commentaire
klb
klb le 2 Juil 2020
Thank you Walter. That solves it!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

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

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by