Thursday, October 11, 2012

How to check if the input is a number (Matlab)

If you are writing a code where the user is asked to give a number, it can be a good idea to check whether or not the inserted value was really a number instead of something else like a letter or some strange character (%, / _ , etc).

The easiest way to do it is asking for a string input and then attempting (via str2num) to make the conversion string to number. If the conversion fails, then the input wasn't a number!


Here a very simple code that does the job.

------------------------------------------------------------------------------------

function [varargout]=CheckIfNumber(s)
%[varargout]=CheckIfNumber(s)
% s is a string
% varargout is the converted number or row vector


num=str2num(s);

if (isempty(num)==0)

    varargout{1}=num;

end

------------------------------------------------------------------------------------

4 comments:

  1. Been searching for ages for this, thank you!

    ReplyDelete
  2. i dont get it, i used that but it showed Undefined function or variable 's'.

    ReplyDelete
  3. how have you used it actually?
    You have just to create a file named CheckIfNumber.m with the text shown above, save it in path that it is accessible by Matlab and call the function typing something like CheckIfNumber(101).
    It works :)

    ReplyDelete

Your comment will be visible after approval.