How to store a specific value in for loop when something happens in that loop
Show older comments
here is one dummy problem regarding my question.
for i=1:5
A(:,:,i) = magic(3)*i;
end
for i = 1:5
for n = 11:100
x(i) = n*A(1,1,i);
if (x>480)
break
end
end
n(i)=n;
end
Now here I want to save all 5 of n values for which x is greater than 480 and it will break loop of n.
1 Comment
Stephen23
on 27 Nov 2015
See Guillaume's answer for an excellent explanation and better solution.
Accepted Answer
More Answers (1)
Your dummy example does not work because you're using the same variable name, n, for indexing and storing the threshold index. If you used any other variable, such as thresholdindex it would work:
thresholdindex = zeros(1, 5);
for i = 1:5
for n = 11:100
if n*A(1,1,i) > 480
break;
end
end
thresholdindex(i) = n;
end
Now a few comments:
- You don't preallocate any of the arrays in your dummy example. Make sure you do in your real code as I've done above.
- Use meaningful variable names. thresholdindex tells the purpose of the variable, n does not.
- Are you sure you need loops? your dummy example could be achieved with this:
n = 11:100;
[~, thresholdindex] = max(bsxfun(@times, squeeze(A(1, 1, :)), 11:100) > 480, [], 2);
thresholdindex = thresholdindex' + n(1)-1
1 Comment
Shaikh Hossain
on 27 Nov 2015
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!