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

22 次查看(过去 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 中查找有关 Introduction to Installation and Licensing 的更多信息

标签

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by