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
0 件のコメント
採用された回答
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Introduction to Installation and Licensing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!