How do I stop the calculation in a for loop?

1 view (last 30 days)
Hello community!
First of all thanks for your help:)
n = 4;
v = rand(n,2);
for f = 1:1000
v = v-0.001
end
Thats already what I ve got. It gives me 1000 of matrixes back and alyways calculated by - 0.001. Now I ve got problem. If one element of the matrix (for example matrix Number 94) is already smaller than 0.001, then this element should be for all other matrixes ( 95 - 1000) equal to zero. I hope you have some advice! Thanks.

Accepted Answer

Walter Roberson
Walter Roberson on 13 Jun 2021
The division by 50 is just to make the output shorter for this demonstration.
format long g
n = 4;
v = rand(n,2) / 50;
for f = 2:1000
temp = v - 0.001;
temp(temp < 0.001) = 0;
v = temp
if ~any(v(:)); break; end %all 0
end
v = 4×2
0.0117169155857542 0.00385373115144157 0.00322072350669969 0.0123980988902088 0.00540972017890342 0.00679499574461224 0.0119082492555772 0
v = 4×2
0.0107169155857542 0.00285373115144157 0.00222072350669969 0.0113980988902088 0.00440972017890342 0.00579499574461224 0.0109082492555772 0
v = 4×2
0.00971691558575421 0.00185373115144157 0.00122072350669969 0.0103980988902088 0.00340972017890342 0.00479499574461224 0.00990824925557724 0
v = 4×2
0.00871691558575421 0 0 0.00939809889020883 0.00240972017890342 0.00379499574461224 0.00890824925557724 0
v = 4×2
0.00771691558575421 0 0 0.00839809889020883 0.00140972017890342 0.00279499574461224 0.00790824925557724 0
v = 4×2
0.00671691558575421 0 0 0.00739809889020883 0 0.00179499574461224 0.00690824925557724 0
v = 4×2
0.00571691558575421 0 0 0.00639809889020883 0 0 0.00590824925557724 0
v = 4×2
0.00471691558575421 0 0 0.00539809889020883 0 0 0.00490824925557724 0
v = 4×2
0.00371691558575421 0 0 0.00439809889020883 0 0 0.00390824925557724 0
v = 4×2
0.00271691558575421 0 0 0.00339809889020883 0 0 0.00290824925557724 0
v = 4×2
0.00171691558575421 0 0 0.00239809889020883 0 0 0.00190824925557724 0
v = 4×2
0 0 0 0.00139809889020883 0 0 0 0
v = 4×2
0 0 0 0 0 0 0 0
  3 Comments
Walter Roberson
Walter Roberson on 13 Jun 2021
p = [r + (a-2*r)*rand(n,1),r + (b-2*r)*rand(n,1)];
v = rand(n,2);
for f = 1:1000
temp = v - 0.001 ;
temp(temp < 0.001) = 0 ;
v = temp ;
if ~any(v(:)); break; end
p = p + v
end

Sign in to comment.

More Answers (0)

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!