Displaying an error message a non-numerical input is inputted in GUI

To be more clear, I'm trying to use GUI in MATLAB for a project. In this project I want the user to input numbers, but if they input a character (like 'a' or 'b', or 'djos') I want there to be an error message to pop up.
Currently I am using:
m = get(handles.filter);
if ~ischar(m)
errordlg('ERROR: Input must be numerical.')
end
I've also used commands "error" and "msgbox", as well as "isnumeric" and "isstring" to no avail. I can get the error message to pop up just fine, however it even gives me the error message for fractions or numbers like "1" and "1/4"!
What am I doing wrong?

 Accepted Answer

m = get(handles.filter, 'String');
d = str2double(m);
if isnan(d)
fprintf('Entry "%s" is not a valid number!\n', m);
return
end
...
However, if you want '1/4' to be permitted, then you are going to have to describe exactly what operations are to be permitted. Is '3+4' okay? '3*4' ? '3.*4' ? '3^4' ? '3^3/4' (and if so should that be 27/4 or 3^(3/4) ?). How about 'sin(1.23)' ? 'pi' ? 'besselk(3,.8)' ?

5 Comments

Walter, thank you for your help.
Do you mean that each and every single operation has to explicitly be permitted? This is only an input for a filter window using the "filter" function in MATLAB, so only whole integers and fractions will be necessary.
I tried inputting your code into my GUI code, however I get error messages for letters AND any numerical input (even 1, or 1/4, or 0.25).
Is '7 3/4' permitted ?
What is handles.filter ? Is it a uicontrol style 'edit' ?
For the input it should be something like "1/4 1/4 1/4 1/4" or "1 1 1 1" as this would be the filter window.
handles.filter is just the edit text object in which I input this filter window. I do not believe it is a uicontrol style 'edit' as I only use this data in order to filter my data.
m = get(handles.filter, 'String');
if ~all(ismember(m, ['0':'9', '/', ' ']))
fprintf('only digits, spaces and / permitted\n');
return
end
parts = regexp(m, '(?<num>-?\d+)/(?<den>\d+)|(?<num>\d+(?!=/))', 'names');
numers = str2double({parts.num});
denoms = cellfun(@(S) str2double([S repmat('1', 1, isempty(S))]), {parts.den});
Now numers and denoms are row vectors of corresponding values. In places the user did not specify a denominator, the value is 1. The numerators may be negative; the denominators may not be. Either one may be 0. They have not been reduced to lowest terms.

Sign in to comment.

More Answers (0)

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!