How to verify that input is numeric in MATLAB - matlab

This is the code that I have written to get the corresponsing alphabetic grade for each numerical grade. I want to make sure that the user doesn't enter any strings or characters as input. Only numbers. So I used isnumeric function but the code doesn't work and the while loop doesn't break when I enter a string. It just give me an error. Would appreciate any help. Thank you.
c=input('What is your grade? ');
while 1
if ~isnumeric(c)
break
end
if c>=90 && c<=100
disp('A');
elseif c<90 && c>=80
disp('B');
else
disp('F');
end
end

Have a look at validateattributes. It is much more powerful than a simple isnumeric, e.g. you can specify a range in which the number should lie: {'>',0,'<',10} or ask themt o be nonnegative
validateattributes(x,{'numeric'},{'nonnegative'})

input evaluates what the user enters*. If what the user enters is not a valid MATLAB expression, then you see an error message. Instead,
c = input('What is your grade? ', 's');
The 's' argument makes it so that the function returns exactly what the user typed, as a string. You can then use str2double to convert that to a number. If it's not a number, NaN will be returned. You can test for this:
while true
c = input('What is your grade? ', 's');
c = str2double(c);
if isnan(c)
break
end
disp(c)
end
* This evaluation actually makes input dangerous to use in this form, for example the user can enter delete('c:/windows') or something like that to destroy your system.

Related

MATLAB String Input If statment

I'm trying to make a program that asks a yes or no question. Based on that answer the program will continue or terminate. I keep getting an error since the arrays don't have the same dimension. I tried to use strcmp() but failed. I don't understand how true or false will help me discriminate between different words and capitalization. (Do I have to test each letter?) I want the program to continue if the input is any of these words 'yes','YES','Yes','y' and quit if the input is 'no','NO','No','n' I really want to understand, the == feels wrong somehow.
Thank You
ZZ=input('Do you want to know when you''ll turn 100?: ', 's');
NN={'no','NO','No','n'}
YY={'yes','YES','Yes','y'}
XX=strcmp(ZZ(NN),ZZ(YY)); %I thought this line would let MATLAB know everything is ok
if ZZ=='no' || ZZ=='NO' || ZZ=='No' || ZZ=='nO' || ZZ=='n'
disp('Thank You.')
disp('Come again.')
elseif ZZ=='yes' || ZZ=='YES'|| ZZ=='Yes'|| ZZ=='y'
x=input('Enter your age: '); %x is your age.
.....
I think if you need your program to run more than once, you need a for or while loop.
zz = 'yes';
while strcmpi(zz(1),'y')
x = input('Enter your age: ');
zz = input('Do you want to know when you''ll turn 100?: ', 's');
end

Matlab ask for integer loop

I'm creating a program to simulate a random walk and it requires the user to input an integer number of steps to take for the walk.
The prompt for this uses code very similar to this:
**% Ask user for a number.
defaultValue = 45;
titleBar = 'Enter a value';
userPrompt = 'Enter the integer';
caUserInput = inputdlg(userPrompt, titleBar, 1,{num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
% Round to nearest integer in case they entered a floating point number.
integerValue = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(integerValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
integerValue = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', integerValue);
uiwait(warndlg(message));
end**
However, I want it to simply display the "Enter a value" prompt again if the user does not enter an integer the first time i.e. 4.4.
Any ideas?
Thanks!
if (mod(integerValue,1) == 0)
will evaluate to true if integerValue is an integer. Simply augment your if statement w/ this logic. You might want to consider changing to using a while loop so the user can enter bad input more than once.
The first answer is totally correct for checking for an integer value, but to address the "show prompt again" issue you can just use a loop conditioning it to get the exact kind of data you want:
caUserInput = nan; %or anything worng for that matter
while isempty(caUserInput) || isnan(caUserInput)
caUserInput = inputdlg(userPrompt, titleBar, 1,{num2str(defaultValue)});
end
if you want you can start it again with different argument lines in a more fancy style:
inputiswrong = 1; %or anything worng for that matter
while inputiswrong
inputiswrong = 0;
caUserInput = inputdlg(userPrompt, titleBar, 1,{num2str(defaultValue)});
if isempty(caUserInput )
userPrompt = 'Try again with an input';
inputiswrong = 1;
end
if isnan(caUserInput )
userPrompt = 'not really a number';
inputiswrong = 1;
end
%and so on
end
In both scenarios you should consider transforming the caUserInput to something you could use, i think inputdlg returns a cell so maybe a cell2mat() around the inputdlg().
Remember that unspecified inputs in MATLAB are double-precision by default. For instance a=3 is not an integer. So you should consider two cases:
Integer type
If you are talking about integer type in MATLAB the easiest way is to use isinteger function by MATLAB:
tf = isinteger(A)
for instance:
isinteger(4.4)
=
0
as I mentioned before, 3 is not an integer:
isinteger(3)
=
0
but this one is integer actually:
isinteger(uint8(3))
=
1
To repeat the input query also easily use the same function in a while loop
while ~isinteger(a)
disp('enter an integer');
....
end
Constant double-precision with no decimal
But if you are considering normal constant inputs to be integers you could convert them to integer and compare the result with the original value:
while a ~= double(int64(a))
disp('enter an integer');
....
end
int64 converts the double type to integer, and double converts it back to double. If in this process the number remains unchanged, then you could consider that it was intended to be an integer.
Recommendation for you specific program
I would use a fix function to get rid of the decimal parts. Usually when you receive a double-precision number including decimal values, the main intention is the the number before the floating point. So in many algorithms it is common practice to use fix to round each element of the given number to the nearest integer toward zero.

if/else statement not executing 'if' statement

I have been trying to print some complex numbers. If the complex number (modTrace) is like 'a-ib' then my code:
modTrace
v = [real(modTrace(:)) imag(modTrace(:))].';
fprintf(fileID,'%e+%ei\n',v);
gives the output as:
2.355387e-13+-7.217925e-13i
To avoid the extra + sign in front of the negative imaginary piece I write:
v = [real(modTrace(:)) imag(modTrace(:))].';
if imag(modTrace(:))>0
fprintf(fileID,'%e+%ei\n',v);
else
fprintf(fileID,'%e%ei\n',v);
end
Now in the output the 'if' is not being executed. So if I have a complex number 'a+ib' it prints
'a bi' and if a complex number is 'a-ib' it prints 'a-bi' according to the else statement.
if I then modify the code like:
v = [real(modTrace(:)) imag(modTrace(:))].';
if imag(modTrace(:))<0
fprintf(fileID,'%e%ei\n',v);
else
fprintf(fileID,'%e+%ei\n',v);
end
then again the 'if' statement in not being executed. So for a complex number 'a-ib' the output is 'a+-bi' and the 'else' statement in being executed correctly.
Could any body please help me to find the output in the correct form?
Thanks.
I think that in this case you are better off using a loop:
for k = 1:length(modTrace)
if imag(modTrace(k))>0
fprintf(fileID,'%e+%ei\n',real(modTrace(k)), imag(modTrace(k)));
else
fprintf(fileID,'%e%ei\n',real(modTrace(k)), imag(modTrace(k)));
end
end
You can't vectorize it that easily because if you pass a vector to if it only evaluates true when (http://www.mathworks.com/help/matlab/ref/if.html):
the result is nonempty and contains all nonzero elements (logical or
real numeric). Otherwise, the expression is false.

special compare in MATLAB

Hi I'm trying to achieve this:
for i=1:maxaps
for j=1:length(num2)
**if (isequal(sortedCell(i),txt2(j)) && sortedCell(i)~=0)** %important line
rssi2sorted(i)=rssi2(j); %I don't think we need matching part
break;
end
end
end
and I receive this error:
??? Undefined function or method 'ne'
for input arguments of type 'cell'.
Error in ==> sortingmethod at 116
if
(isequal(sortedCell(i),txt2(j))
&& sortedCell(i)~=0)
if I try like this:
for i=1:maxaps
for j=1:length(num2)
**if (isequal(sortedCell{i},txt2(j)) && sortedCell(i)~=0)** %important line
rssi2sorted(i)=rssi2(j); %I don't think we need matching part
break;
end
end
end
the elements can't be compared because of the format:
>> sortedCell{1}
ans =
00:1e:58:f4:15:f7
>> txt2(6)
ans =
'00:1e:58:f4:15:f7'
any recommendations on how to fix this?
Thanks!
I believe that the issue is actually with this part (the ne that your error refers to):
sortedCell(i)~=0
You're comparing a cell, rather than its contents, to zero. You should use:
sortedCell{i}~=0
EDIT:
If the question is not about the error message, but rather how to compare strings, just use strcmp (never use ==, eq, or isequal to compare strings):
if strcmp(sortedCell{i},txt2(j))
...
end
I don't know what the && sortedCell{i}~=0 part you've added is for, but you can add it back if needed.
strcmp also take cell arrays as inputs (see the documentation) so you may be able to get rid of on of your for loops. I don't know what your code does, but maybe you you could use something like this:
for j=1:length(num2)
c = strcmp(sortedCell,txt2(j));
if any(c)
rssi2sorted(c)=rssi2(j);
break;
end
end
use strcmp (of strcmpi ignoring case) to test is strings are the same, isequal is for testing if values are numerically equal. e.g.
if ( strcmp(sortedCell{i},txt2(j)) && sortedCell(i)~=0 )

how to make matlab detect incompatible type assignments?

hi have a major problem in matlab. I have a function and it sometimes returns control ascii characters. How do i check for the presence of these control ascii ?.
my code looks like this
d = out.autoc
d sometimes receives control ascii characters instead of a actual double value. Does someone know how to catch such incompatible assignments ?
I think this should work but you may want to double check the ASCII codes to exclude.
%here I load Ctrl-C
s = sprintf('%s', 3);
code = bin2dec(dec2bin(s,8));
if code < 32
fprintf('ignore');
else
fprintf('do somsething');
end
If you want to check that the value of d is double, and not a string. You can check it this way:
if ~isnumeric(d) || ~isdouble(d)
fprintf('d is not of class double\n');
end
But if you want to assign the value of out.autoc to d only if out.autoc is double, you can do this:
if isnumeric(out.autoc) && isequal(class(out.autoc), 'double')
d = out.autoc;
else
fprintf('out.autoc is not of class double, no assignment made.\n');
end