Move on to next iteration when condition is satisfied, specifically when using functions
Show older comments
for i1 = 1:10
[out1,out2] = func1(in1,in2) % in1 is file name for 10 files in directory
end
func1 analyzes some files which can be analyzed, but I want it to skip files which cannot
function [out1,out2] = func1(in1,in2)
if strcmp(in1,'File #1') % check that in1 (input file name) is File #1
% do some analysis
end
if strcmp(in1,'File #2')
% do some analysis
end
if strcmp(in1,'File #3')
continue % I want to skip analysis of File #3 and continue/move on to File #4 in the above for loop
end
% rest of the files
end
the error I get is "A CONTINUE may only be used within a FOR or WHILE loop."
I understand what the error means, but want to ask how I can accomplish the same goal, of continueing a for loop outside the function when a condition is met.
The analyses require some manual identification of parameters, such as window indices, so I have to input them manually each time.
Accepted Answer
More Answers (1)
It's better to use elseif in the form below. A 'return' will stop execution of the function and return execution to the caller.
function [out1,out2] = func1(in1,in2)
if strcmp(in1,'File #1') % check that in1 (input file name) is File #1
% do some analysis
elseif strcmp(in1,'File #2')
% do some analysis
elseif strcmp(in1,'File #3')
out1 = NaN; %or whatever the default output is
out2 = NaN; %or whatever the default output is
return % <--------------------------- stop and go back to caller
elseif
%... rest of the files
end
end
*Updated to add default outputs. The default outputs can also be defined prior to the conditionals in order to ensure that they exist prior to returning.
4 Comments
Walter Roberson
on 2 Oct 2019
When you have outputs like you do, make sure that something has been assigned to the outputs before you return.
Adam Danz
on 2 Oct 2019
ah.... good catch... I'm going to update the answer to reflect that common mistake.
Z Liang
on 3 Oct 2019
Adam Danz
on 3 Oct 2019
As Stephen Cobeldick mentioned, the 'return' merely exits the body_metric() funciton. The default "NaN" values I added were just an example. You should define the default values in a smarter way. NaNs could be the best solution but that depends on the expected size/shape of the data and how you're going to process it. Maybe the default should be 0s or empties [ ]. That's up for you to decide. The mean() function can handle empty values as well as NaNs (see "omitnan" option).
Categories
Find more on Data Import from MATLAB 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!