Putting 2 variables in an if loop

5 次查看(过去 30 天)
andrea vivas
andrea vivas 2021-4-22
回答: DGM 2021-4-22
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

回答(1 个)

DGM
DGM 2021-4-22
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

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by