MATLAB for loop and nested if commands

5 次查看(过去 30 天)
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
VBBV 2024-2-23
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 个评论
VBBV
VBBV 2024-2-23
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by