Putting 2 variables in an if loop

5 Ansichten (letzte 30 Tage)
andrea vivas
andrea vivas am 22 Apr. 2021
Beantwortet: DGM am 22 Apr. 2021
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

Antworten (1)

DGM
DGM am 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by