How to stop running the code for conditional logical output?

6 views (last 30 days)
I am writing a function with multiple outputs. The first one being a logical output. I do not need further outputs if logical output is 0. I am wondering what is the best way to stop running the code if logical output is 0? I used this code, it seems like working.
logical_out = ~isempty(subject_in_feeder);
% don't need further analysis if output is 0
if logical_out == 0
return
end
% further analysis
terminal_coordinatetimes = [subject_in_feeder.coordinatetimes(1), ...
subject_in_feeder.coordinatetimes(end)]';

Accepted Answer

Voss
Voss on 1 Apr 2022
Using return like that is completely appropriate for what you want to do, but you must make sure all of your function's outputs are defined when the function returns. The second output may not be used in case the first one is false or 0, but the second one has to have a value anyway.
[result1,result2] = my_function([])
result1 = logical
0
result2 = []
function [logical_out,terminal_coordinatetimes] = my_function(subject_in_feeder)
logical_out = ~isempty(subject_in_feeder);
% don't need further analysis if output is 0
if logical_out == 0
% have to return some value for terminal_coordinatetimes
terminal_coordinatetimes = [];
return
end
% further analysis
terminal_coordinatetimes = [subject_in_feeder.coordinatetimes(1), ...
subject_in_feeder.coordinatetimes(end)]';
end

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!