필터 지우기
필터 지우기

Find logical and (&&) for string array

조회 수: 17 (최근 30일)
Mikel Jimenez
Mikel Jimenez 2023년 2월 24일
댓글: Mikel Jimenez 2023년 2월 25일
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.

채택된 답변

Steven Lord
Steven Lord 2023년 2월 24일
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
z = 10
arrayX = "Right";
arrayY = "Left";
if arrayX=="Left" && arrayY=="Right"
z=10
elseif arrayX=="Right" && arrayY=="Left"
z=20
end
z = 20
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
This code threw error: Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to reduce operands to logical scalar values.
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
This code threw error: Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to reduce operands to logical scalar values.
Both code segments threw the same error.

추가 답변 (1개)

Dyuman Joshi
Dyuman Joshi 2023년 2월 24일
편집: Dyuman Joshi 2023년 2월 24일
Use strcmp or isequal to compare strings
str1 = "Left";
str2 = "Right";
if strcmp(str1,"Left") && strcmp(str2,"Right")
z=10
elseif strcmp(str1,"Right") && strcmp(str2,"Left")
z=20
end
z = 10
  댓글 수: 1
Mikel Jimenez
Mikel Jimenez 2023년 2월 25일
Thanks Dyuman, this seems to be working too.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by