Putting 2 variables in an if loop
5 views (last 30 days)
Show older comments
Hey I'm trying to build an if loop and instead of repeating the same line over and over again I wanted to see if there is anyway of puttigs on variable equal to two values (in my case names). I tried putting the names in brackets but it gives me an answer = logical 0 whoch I do not want I want only the fprintf statement to appear after entering the variable value. Please let me know if you have a solution

0 Comments
Answers (1)
DGM
on 22 Apr 2021
Doing direct comparison with strings isn't really going to work that way; certainly not with that syntax. A string is just a character vector. If you try to compare two vectors of unequal length for equality, you'll get an error. If you do this:
D = ['A','B','C'];
Then that's just going to concatenate them. D is 'ABC'.
Use strcmp(), strcmpi(), ismember() etc for handling string comparison. If you're going to test a lot of cases, you can just avoid all that and do this.
switch mystring
case 'this'
% do a thing
case 'that'
% do a different thing
case {'another','thing'}
% do something else
end
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements 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!