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

22 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Kevin Phung
Kevin Phung el 8 de Mzo. de 2019
Editada: Kevin Phung el 8 de Mzo. de 2019
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 comentarios
Dan Hallatt
Dan Hallatt el 8 de Mzo. de 2019
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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Introduction to Installation and Licensing en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by