1

I have these lines of code:

someFunction
disp('This should not be executed, if condition in someFunction is 
true')


function someFunction
if condition
% what do I have to write here so the disp command is not executed?
% return does not do it. I don't want to throw an error.  quit/exit 
% are also not what I want..
end

What statement do I need in the if condition block so the disp statement is not executed if condition is true? error('some error') would do it. But I don't want to throw an error.

Anton Rodenhauser
  • 441
  • 1
  • 3
  • 11
  • Perhaps [this](https://stackoverflow.com/q/10033078/52738) would work for you? – gnovice Sep 27 '17 at 21:27
  • The common way to do this is using a returned argument from `someFunction`. If this won't work for your problem you need to give more details as to why. – buzjwa Sep 28 '17 at 10:53
  • @gnovice yes that was indeed helpful. But the approach there is way to complicated for my case. I ll just use a returned argument in someFunction.. aka `isOk = someFunction` – Anton Rodenhauser Sep 28 '17 at 18:16

1 Answers1

1

May be I do not get the question properly, by I'd recommend an approach used in device interfacing in C. Let us suggest we have a function that calls some other functions which communicate to a device and return int value: deviceOk (usually 0) or error code. If any internal function fails, we should terminate the calling function and go to resource management. The resulting function is full of checks, nested or sequential.

function isOk = mainFcn()
isOk = false; 
% awaiting a bad result is better if we suppose a crash or exception somewhere inside, but wan a clean exit
[isOk , result] = someFcn(input);
if (~isOk)
   disp('If everything was OK, I'd never see this message');
end
end

function [isOk, result] = someFcn(input)
isOk = false; %preallocate inputs to error and modify only if really needed
result = Nan;
if isnan(result)
   return;
end
end
Gryphon
  • 549
  • 3
  • 14
  • yes, it seems like this is the way to go.. I was hoping there would be an easy command that works just like control + c, only in the code. But that doesn't seem to be the case.. I ll use your approach now instead.. – Anton Rodenhauser Sep 28 '17 at 18:14
  • in fact there is a `goto` [implementation](https://www.mathworks.com/matlabcentral/fileexchange/26949-matlab-goto-statement) in FEX, but I don't think it will be much better – Gryphon Sep 28 '17 at 18:53