MATLAB String Input If statment - matlab

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

Related

How to verify that input is numeric in 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.

How to return boolean in if else statement and the return value will link to anothe if else statement in Matlab?

I have the following if else statement that created by myself in order to link to the if else statement given in second part:
m=4
if m==3
disp(true)
else
disp(false)
Second part ( this code is fix cannot be change):
if (true)
A=Hello World
else
A=Bye
If using the first part code, my output will be
A=Hello World
but my desire output is
A=Bye
Anyone one have idea to edit the first part, because now my return value in first part not able to link to my second part.
If you can't change the second part's code, I'm afraid your desire cannot be fulfilled. Or rather, I'm afraid your code won't run at all, because your perenthesis, quotes, end-statement (and arguably semicolons) are not in place.
if true
A = 'Hello World';
else
A = 'Bye';
end
This code will return A = 'Hello World', no matter what, since true is always true. If-else conditions work like this:
if (*what's in here evealuates to true*)
%do stuff
else (*if what's up there does not evaluate to true*)
%do other stuff
Clearly, true will always evaluate to true. So the above if-else condition will always return A = 'Hello World'.
You don't need two if statements in order to accomplish this task. One is more than enough to perform all what you need:
m = 4;
if (m == 3)
A = 'Hello World';
else
A = 'Bye';
end
disp(A);
A few comments concerning your code:
if statements need to be closed with an end
if (true) will always pass into the statement
the disp function doesn't assign a value, its only goal is to display it in the Command Window
in order to work with text, you have to enclose it within single quotes ' (char array) or double quotes " (string), more info here
If you posted only small excerpts of your code and you need to perform those two checks sequentially, in different parts of your script, then:
m = 4;
if (m == 3)
m_equals_3 = true;
disp('M == 3');
else
m_equals_3 = false;
disp('M ~= 3');
end
% then, somewhere else...
if (m_equals_3)
A = 'Hello World';
else
A = 'Bye';
end
% ...
I guess this is a homework exercise. You should disclose that if it’s the case.
The exercise requieres you to change the workspace such that the second bit of code evaluated the else case. This can be accomplished by changing the meaning of true. In your first bit of code, make it so that
true = flase;
Or equivalently,
true = 0;
Note that this is really bad form, if you ever do something like this outside of a homework exercise that explicitly asks you to do so, you’ll get fired or maybe even shot. You’ve been warned!
By the way, I assume that the missing quote characters around the strings and the missing ends are typos?

If and elseif, only the first line work?

L=1; Nx=51; PeriodicFlag=1; T=15; Nt=51;
spacedef='Pade6FirstDeriv'; casedef='LinearAdvection';
if (spacedef == 'Pade6FirstDeriv')
D1 = sparse(Pade6(Nx,dx,PeriodicFlag));
elseif (spacedef == 'Upwind3FirstDeriv')
D1 = sparse(Upwind3(Nx,dx,PeriodicFlag));
elseif (spacedef == 'Central4FirstDeriv')
D1 = sparse(Central4(Nx,dx,PeriodicFlag));
elseif (spacedef == 'Central2FirstDeriv')
D1 = sparse(Central2(Nx,dx,PeriodicFlag));
else
error(sprintf('Unknown spacedef = %s',spacedef));
end
In the above code, the if section is a small segment from a function I've constructed. I'm trying to get the function to know which methods to use based on my input (spacedef). Central2, Central4, Upwind3, and Pade6 are other functions I've written. The weird thing is that when spacedef =/= to 'Pade6FirstDeriv', I would get an error stating Error using ==, Matrix dimensions must agree. I've tried swapping the order of the if loop (by placing Central4, Central2, Pade6, and Upwind3 in the first line of the loop), and it seems like only the top line of the loop will work (the elseifs are not working). I'd greatly appreciate it if anybody can help me out. Thanks!
As has been noted in the comments, this is a common error when people first start comparing strings in MATLAB, and strcmp or strcmpi is generally the solution.
However, one solution the questions links in the comments don't present, and a solution I think looks much nicer, is the switch statement:
switch (spacedef)
case('Pade6FirstDeriv')
D1 = sparse(Pade6(Nx,dx,PeriodicFlag));
case('Upwind3FirstDeriv')
D1 = sparse(Upwind3(Nx,dx,PeriodicFlag));
case('Central4FirstDeriv')
D1 = sparse(Central4(Nx,dx,PeriodicFlag));
case('Central2FirstDeriv')
D1 = sparse(Central2(Nx,dx,PeriodicFlag));
otherwise
error(sprintf('Unknown spacedef = %s',spacedef));
end
Note: if I expect others to use my code with string comparisons, I usually lower the input such that the comparison is case-insensitive, although I have not done that here.

Creating a translator in MatLab

I am trying to create a simple program in Matlab where the user can input a string (such as "A", "B", "AB" or "A B") and the program will output a word corresponding to my letter.
Input | Output
A Hello
B Hola
AB HelloHola
A B Hello Hola
This is my code:
A='Hello'; B='Hola';
userText = input('What is your message: ', 's');
userText = upper(userText);
for ind = 1:length(userText)
current = userText(ind);
X = ['The output is ', current];
disp(X);
end
Currently I don't get my desired results. I instead get this:
Input | Output
A The output is A
B The output is B
I'm not totally sure why X = ['The output is ', current]; evaluates to The output is A instead of The output is Hello.
Edit:
How would this program be able to handle numbers... such as 1 = "Goodbye"
What's going on:
%// intput text
userText = input('What is your message: ', 's');
%// ...and some lines later
X = ['The output is ', userText];
You never map what you type to what is contained by the variables A and B.
The fact that they are called A and B has nothing to do with what you type. You could call them C and blargh and still get the same result.
Now, you could use eval, but that's really not advisable here. In this case, using eval would force the one typing in the strings to know the exact names of your variables...that's a portability, maintainability, security, etc. disaster waiting to happen.
There are better solutions possible, for instance, create a simple map:
map = {
'A' 'Hello'
'B' 'Hola'
'1' 'Goodbye'
};
userText = input('What is your message: ', 's');
str = map{strcmpi(map(:,1), userText), 2};
disp(['The output is ', str]);
I would recommend using a map object to contain what you want. This will circumvent the eval function (which I suggest avoiding like the plague). This is pretty simple to read and understand, and is pretty efficient especially in the case of a long input string.
translation = containers.Map()
translation('A') = 'Hola';
translation('B') = 'Hello';
translation('1') = 'Goodbye';
inputString = 'ABA1BA1B11ABBA';
resultString = '';
for i = 1:length(inputString)
if translation.isKey(inputString(i))
% get mapped string if it exists
resultString = [resultString,translation(inputString(i))];
else
% if mapping does not exist, simply put the input string in (covers space case)
resultString = [resultString,inputString(i)];
end
end
Take a look at the command eval. Currently, you are displaying the name of the variable that contains the string you want. eval will help you in actually accessing and printing it.
What you need to do it :
X = ['The output is ', eval(current)];
Here the documentation : eval

How to avoid enter any i and j value when numeric input is required in matlab

Consider I have
a = input(value = );
how can I prevent user from enter i and j as the input values. I would like to have a code some thing like tat
if a == any value involves i and j
then break or terminate
and prompt the function a = input(value = ) again.
between I have tired something like this, but it doesn't work (the error is still coming out and it unable to prompt the second defined input a = input('enter again')), can anybody explain to me where's the mistake I have done.
if ~isnan(x) || ~isnumeric
a = input('enter again');
else
continue
end
I will really appreciate all the help.
Try the following to keep on pressing user to enter the values that abide by your conditions. As per my comment, the post gives a great idea of how you can achieve this. It is not using OR but AND to have a firm condional validation.
while ~(~isempty(a) ...
&& isnumeric(a) ...
&& isreal(a) ...
&& isfinite(a) ...
&& (a == fix(a)) ...
&& (a > 0))
a = input('Enter the number of dice to roll: ');
end
try this
a = NaN;
while isnan(a) || ~isreal(a)
a = input('value=','s');
a = str2double(a);
end