Find logical and (&&) for string array
23 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Mikel Jimenez
il 24 Feb 2023
Commentato: Mikel Jimenez
il 25 Feb 2023
Hi,
I normally use && operations with numeric arrays, like:
if arrayX==1 && arrayY ==2
z=10
elseif arrayX==2 && arrayY==1
z=20
end
Now, I'm trying to do the same thing with string arrays, but cannot find the way to do it correctly, the && operand does not work here. Example:
if arrayX=="Left" && arrayY=="Right"
z=10
elseif arrayX=="Right" && arrayY=="Left"
z=20
end
Any help with this very much appreciated.
Thanks.
0 Commenti
Risposta accettata
Steven Lord
il 24 Feb 2023
That should work as long as the string arrays you're using in your comparisons are scalars.
arrayX = "Left";
arrayY = "Right";
if arrayX=="Left" && arrayY=="Right"
z=10
elseif arrayX=="Right" && arrayY=="Left"
z=20
end
arrayX = "Right";
arrayY = "Left";
if arrayX=="Left" && arrayY=="Right"
z=10
elseif arrayX=="Right" && arrayY=="Left"
z=20
end
It won't work if they're non-scalar string arrays, just like it wouldn't work with numeric arrays if they were non-scalar. I've wrapped each of these code segments in a try / catch block so I can show you the same behavior with both a non-scalar string array and a non-scalar numeric array.
try
arrayX = ["Left", "Left"];
arrayY = "Right";
if arrayX=="Left" && arrayY=="Right"
z=10
elseif arrayX=="Right" && arrayY=="Left"
z=20
end
catch ME
fprintf("This code threw error:\n%s\n", ME.message)
end
try
arrayX = [1 2];
arrayY = 2;
if arrayX==1 && arrayY ==2
z=10
elseif arrayX==2 && arrayY==1
z=20
end
catch ME2
fprintf("This code threw error:\n%s\n", ME2.message)
end
Both code segments threw the same error.
0 Commenti
Più risposte (1)
Vedere anche
Categorie
Scopri di più su Whos in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!