# MATLAB for loop and nested if commands

8 views (last 30 days)
Hong on 23 Feb 2024
Commented: VBBV on 23 Feb 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.

VBBV on 23 Feb 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
Hong on 23 Feb 2024
thank you
VBBV on 23 Feb 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