How do I use the OR "||" operator in an 'if' statement on multiple possible strings?

조회 수: 45 (최근 30일)
Hello, I am looking to categorize a collection of strings that I have stored in a vector ('Names') depending on their values. For example, for each element in the vector (which is a string, such as 'Na', or 'K', or 'Pb', etc.) if the element is a certain type of element I want to do something, whereas if it is a different type of element I want to do something else. I understand how to do this for scalar values using an 'if' statement, but there is the common error that pops up if the if statement uses the OR '||' operator on strings instead: "Operands to the || and && operators must be convertible to logical scalar values.".
This is what I am trying to do:
for i = 1:length(Names)
if Names(i) == 'Pu' || 'Am' || 'Np' || 'Cm' ; %actinides
Yield.CData(i,:) = [255 0 0]; %red for actinides
elseif Names(i) == 'Mo' || 'Ru' || 'Tc' || 'Rh' ; %noble metals
Yield.CData(i,:) = [0 255 0]; %green for noble metals
elseif Names(i) == 'Ce' || 'Nd' || 'Eu' || 'Sm' ; %lanthanides (R.E.E.)
Yield.CData(i,:) = [255 255 0]; %yellow for lanthanides (R.E.E.)
elseif Names(i) == 'Li' || 'Na' || 'K' || 'Rb' || 'Cs' || 'Fr' ; %alkali-metal halides
Yield.CData(i,:) = [0 0 0]; %black for alkali-metal halides
else if Names(i) == 'O' || 'Xe' || 'Te'; %non-metals
Yield.CData(i,:) = [255 255 255]; %white for non-metals
else
end
end
end
If someone could please give me an answer or some insight I would very grateful!
~ Dan

채택된 답변

Kevin Phung
Kevin Phung 2019년 3월 8일
편집: Kevin Phung 2019년 3월 8일
I would suggest using switch / case, it's a lot more intuitive to look at:
for i = 1:length(Names)
switch Names(i)
case{'Pu','Am','Np','Cm'}
Yield.CData(i,:) = [255 0 0];
case{'Mo','Ru','Tc','Rh'}
Yield.CData(i,:) = [0 255 0];
case{'Ce','Nd','Eu','Sm'}
Yield.CData(i,:) = [0 255 0];
case{'Li','Na','K','Rb','Cs','Fr'}
Yield.CData(i,:) = [0 0 0];
case{'O','Xe','Te'}
Yield.CData(i,:) = [255 255 255];
end
end
if you really wanted to use the if / else method, you should use strcmp:
if any(strcmp(a,{'Pu','Am','Np','Cm'}))
%...
end
  댓글 수: 2
Dan Hallatt
Dan Hallatt 2019년 3월 8일
This worked beautifully thank you. I had never heard of switch/case before but it seems quite powerful after a quick read on it. Thank you! I will impliment this into many other parts of my code to add flexibility.

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

추가 답변 (0개)

카테고리

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

태그

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by