Clear Filters
Clear Filters

MATLAB for loop and nested if commands

5 views (last 30 days)
Hong
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.

Accepted Answer

VBBV
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
  2 Comments
VBBV
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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!