MATLAB for loop and nested if commands

16 vues (au cours des 30 derniers jours)
Hong
Hong le 23 Fév 2024
Commenté : VBBV le 23 Fév 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.

Réponse acceptée

VBBV
VBBV le 23 Fév 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 commentaires
Hong
Hong le 23 Fév 2024
thank you
VBBV
VBBV le 23 Fév 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by