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

22 ビュー (過去 30 日間)
Dan Hallatt
Dan Hallatt 2019 年 3 月 8 日
コメント済み: Kevin Phung 2019 年 3 月 8 日
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.
Kevin Phung
Kevin Phung 2019 年 3 月 8 日
you're welcome! happy to help.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeIntroduction 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