How to store a specific value in for loop when something happens in that loop

2 views (last 30 days)
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.

Accepted Answer

KSSV
KSSV on 26 Nov 2015
for i=1:5
A(:,:,i) = magic(3)*i;
end
count = 0 ;
iwant = [];
for i = 1:5
for n = 11:100
x(i) = n*A(1,1,i);
if (x>480)
count = count+1 ;
iwant(count) = n ;
break
end
end
n(i)=n;
end
Note: Considering allocating the matrices at the begin

More Answers (1)

Guillaume
Guillaume on 26 Nov 2015
Edited: Guillaume on 26 Nov 2015
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

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!