How to specify a stop criterion in an if loop.

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

Sign in to comment.

Accepted Answer

Image Analyst
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
elseif NFile(i)>1
if TData(j)<RData(i)
NewRData(i)= TRData(j)
% Break out of the j loop (but not the i loop);
abort = true; % Set flag indicating we need to quit both loops.
% Now check if we need to break out of the i loop:
if abort
break; % break out of the i loop.
Adapt as needed.

More Answers (0)


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!