if statement with vector

32 visualizaciones (últimos 30 días)
Ireedui Ganzorig
Ireedui Ganzorig el 12 de Mzo. de 2020
Comentada: Ireedui Ganzorig el 12 de Mzo. de 2020
Hello MATLAB community,
Everything was just working when temps was a scalar; however, I couldn't figure out why my code is not giving me 3 corresponding results for the vector temps. I am expecting 3 answers such that -1 is solid, 1 is liquid and 101 is gas.
Thank you.
temps = [-1 1 101];
F = 9/5 .* temps + 32;
if F <= 32
disp(['The Fahrenheit temperature is ', num2str(F)])
disp('solid')
elseif F > 212
disp(['The Fahrenheit temperature is ',num2str(F)])
disp('gas')
elseif F < 212 && F > 32
disp(['The Fahrenheit temperature is ',num2str(F)])
disp('liquid')
end

Respuestas (1)

Bhaskar R
Bhaskar R el 12 de Mzo. de 2020
You are checking all values in the if conditioning, it gives pass condition if and only of all values are true, to avoid your situation use for loop to check each value of F
temps = [-1 1 101];
F = 9/5 .* temps + 32;
for ii=1:length(F)
if F(ii) <= 32
disp(['The Fahrenheit temperature is ', num2str(F(ii))])
disp('solid')
elseif F(ii) > 212
disp(['The Fahrenheit temperature is ',num2str(F(ii))])
disp('gas')
elseif F(ii) > 32 & F(ii)< 212
disp(['The Fahrenheit temperature is ',num2str(F(ii))])
disp('liquid')
end
end
  1 comentario
Ireedui Ganzorig
Ireedui Ganzorig el 12 de Mzo. de 2020
thank you very much. I really appreciate it.

Iniciar sesión para comentar.

Categorías

Más información sobre Instrument Control Toolbox en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by