Steeven
Steeven

Reputation: 4200

MatLab: Error handling of integer input

How do I in MatLab catch the error that occours when the user enters letters and other things that aren't numbers in the input:

width = input('Enter a width: ');

I have played around for a while with the try/catch command:

width = 0;
message = '';

% Prompting.
while strcmp(message,'Invalid.') || width < 1 || width ~= int32(width)

  try
     disp(message)
     width = input('Frame width: ');
  catch error
     message = 'Invalid.';
  end

end

But with no luck (the above doesn't work). As shown I would like a simple message like "Frame width: " for the user the first time he has to enter his choice. But if an error is caught I want the message for him to be "Invalid. Try again: " fx everytime an error occours.

I have also tried the error() but I don't know how to place that correctly. Since the error() doesn't take the input command, where the error happends, as an argument, it must detect it in another way, which I can't figure.

Any help would be appreciated.

Upvotes: 1

Views: 1917

Answers (2)

kol
kol

Reputation: 28698

answer = input('Frame width: ', 's');
[width, status] = str2num(answer);
while ~status || ~isscalar(width) || width ~= floor(width)
  answer = input('Invalid. Try again: ', 's');
  [width, status] = str2num(answer);
end
disp(width);

(status is 0 if the conversion failed. Without the isscalar test, an input like [1 2; 3 4] would also be accepted. The last test ensures that width must be an integer.)

Upvotes: 2

Gunther Struyf
Gunther Struyf

Reputation: 11168

width = input('Frame width: ');
while(~isInt(width))
    width = input('Invalid. Try again: ');
end

and you'll have to have the following function somewhere (or another implementation of it)

function retval = isInt(val)
    retval = isscalar(val) && isnumeric(val) && isreal(val) && isfinite(val) && (val == fix(val));
end

Upvotes: 4

Related Questions