# How to specify a stop criterion in an if loop.

2 views (last 30 days)
Lewis Waswa on 3 Jul 2021
Commented: Lewis Waswa on 9 Jul 2021
I have two files named TData (j) (technical Data) and RData (i) in an array format. I also have a file NFile (i), which is supposed to specify an operation condition as follows. If an index of NFile is greater than 1, we define a newfile, NewRData (i) as the value of TData (j) that is IMMEDIATELY less than or equal to RData(i).
I have written the following code and the code seems to stop at the last value of the TData instead of the immediate less value of TData.
RData =[0.443 0.641 0.641 0.641 0.641 0.641] % 6 by 1 column matrix
NFile= [0.93 0.95 0.97 0.99 1.02 1.01] % 1 by 6 row matrix
TData =[1.2 0.87 0.64 0.44 0.32 0.25 0.21] % 7 by 1 column matrix
for i=1:size(RData,1)
for j=1:size(TData,1)
if NFile(i)>1
if TData(j)<RData(i)
NewRData(i)= TRData(j)
else
NewR(i)=R(i)
end
end
end
based on the above file, my NewR should be [0.443 0.641 0.641 0.641 0.44 0.44]
However my program give NewR as [0 0 0 0 0.21 0.21]. Kindly help me trouble shoot it. What am I missing?
Lewis Waswa on 9 Jul 2021
@Walter Roberson, indeed. All I needed was a break after line seven and did not have to use the initializer. Thank you

Image Analyst on 3 Jul 2021
Assuming your code is otherwise correct, you'll need to use the break command twice : once to break out of the inner loop, and then once out of that, again to break out of the outer loop:
abort = false; % Clear flag.
for i=1:size(RData,1)
for j=1:size(TData,1)
if NFile(i)<1
NewRData(i)=R(i)
elseif NFile(i)>1
if TData(j)<RData(i)
NewRData(i)= TRData(j)
i=1
% Break out of the j loop (but not the i loop);
abort = true; % Set flag indicating we need to quit both loops.
break;
end
end
end
% Now check if we need to break out of the i loop:
if abort
break; % break out of the i loop.
end
end
Lewis Waswa on 9 Jul 2021
Thank you. This worked with a bi of tweaking.

R2020a

### Community Treasure Hunt

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

Start Hunting!