Clear Filters
Clear Filters

Nested loop error and saving result

2 views (last 30 days)
klb
klb on 2 Jul 2020
Commented: klb on 2 Jul 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.

Accepted Answer

Walter Roberson
Walter Roberson on 2 Jul 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.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!