Kamran Bigdely
Kamran Bigdely

Reputation: 8466

How to exit a matlab m-file (NOT the matlab itself) if the user enters bad inputs?

How to exit a matlab m-file (NOT the matlab itself) if the user enters bad inputs? I know if a m-file goes wrong at run time we can press Ctrl-C to stop it. but I need a command to put it in my m-file to do so if something bad happens.

Please don't suggest 'exit' or 'quit' commands as they terminate the entire matlab and I don't want it.

Upvotes: 13

Views: 28000

Answers (3)

Dan
Dan

Reputation: 431

Hey I suppose you could use a try-catch combination to handle a somewhat unexpected error and do something about it.

As an example,

function [ output ] = test(input)

  Bmat = [ 1 1 1 ]   % Some matrix

  try
    input*B;
  catch ME
    disp(ME.message)
    return;          % This is the statement that exits your function
  end

end

If you run

>> test([1 1 1])

It won't work since the variables 'input' and 'B' have mismatched inner dimensions, but the 'try' statement will throw an exception to 'catch', and do whatever you want from there. In this case, it will display an error message at the command line and exit the function.

The variable 'ME' here is just a MATLAB object for error handling, and ME.message stores a string containing the type of error the interpreter caught.

I just read your question again... I assume the command 'return' is probably what you are really after, you will be able use it to exit from any logic or loop statements, as well as functions.

You can read more about the 'return' command and error handling from the MATLAB documentation,

http://www.mathworks.com/access/helpdesk/help/techdoc/ref/return.html

Upvotes: 7

YYC
YYC

Reputation: 1802

I am not sure how you define "exit", but error seems to be the function you need.

y = input('Please input a non-negative number: ');
if(y<0)
    error('input must be non-negative');
end

disp( sprintf('y=%f', y ) );

Upvotes: 13

Xzhsh
Xzhsh

Reputation: 2239

You can just put a error command like error('bad user input') and it should stop the script.

Edit: alternatively, you could just refactor your code to not run unless you set the input flag to be true. Something like

inp = input('>', s)

if validateInput(inp)
    %do you stuff here or call your main function
else
    fprintf('Invalid input')
end

Upvotes: 6

Related Questions