MATLAB for loop and nested if commands

16 visualizaciones (últimos 30 días)
Hong
Hong el 23 de Feb. de 2024
Comentada: VBBV el 23 de Feb. de 2024
A vector is given by: v=[6, 3, -9, 10, 5, 0, -8, 11, -5]. Write a MATLAB program that uses a for loop and nested if statements to divide each positive even element of v by 2, multiply each positive odd element of v by 2, and square (i.e. raise to power 2) each of its negative elements. Then it should output the new vector to the screen as: The new vector is: 3 6 81 5 10 0 64 22 25
Hi, I tried to do this specific question but I always get the exact same old vector and I do not understand how for loop works eventhough I tried to look it up on Youtube. The example is way more easy than the question I got.

Respuesta aceptada

VBBV
VBBV el 23 de Feb. de 2024
v = [6, 3, -9, 10, 5, 0, -8, 11, -5];
for k = 1:length(v)
if mod(v(k),2)== 0 & v(k) > 0
v(k) = v(k)/2;
elseif mod(v(k),2) ~= 0 & v(k) > 0
v(k) = v(k)*2;
elseif v(k)<0
v(k) = v(k)^2;
end
end
v
v = 1x9
3 6 81 5 10 0 64 22 25
  2 comentarios
Hong
Hong el 23 de Feb. de 2024
thank you
VBBV
VBBV el 23 de Feb. de 2024
you can use sprintf /fprintf to display the vector to a screen as below
v = [6, 3, -9, 10, 5, 0, -8, 11, -5];
for k = 1:length(v)
if mod(v(k),2)== 0 & v(k) > 0
v(k) = v(k)/2;
elseif mod(v(k),2) ~= 0 & v(k) > 0
v(k) = v(k)*2;
elseif v(k)<0
v(k) = v(k)^2;
end
end
fprintf('The new vector is : %d %d %d %d %d %d %d %d %d',v)
The new vector is : 3 6 81 5 10 0 64 22 25

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by