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
------------------------------------------------------------------------------------
Been searching for ages for this, thank you!
ReplyDeleteYou're welcome!
Deletei dont get it, i used that but it showed Undefined function or variable 's'.
ReplyDeletehow have you used it actually?
ReplyDeleteYou 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 :)