Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 328
Kamran Bigdely Avatar asked Aug 04 '10 18:08

Kamran Bigdely


People also ask

How do I stop an M file from running in Matlab?

To stop execution of a MATLAB® command, press Ctrl+C or Ctrl+Break.

How do I close an M file?

You can use return in your script and function to exit.


3 Answers

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 ) );
like image 108
YYC Avatar answered Sep 17 '22 18:09

YYC


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

like image 20
Dan Avatar answered Sep 18 '22 18:09

Dan


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
like image 33
Xzhsh Avatar answered Sep 17 '22 18:09

Xzhsh