Question about for loop

I'm trying to solve this question.
A vector is given by x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5]. Using conditional statement and loops, write a program that crates two vectors from x- one(P) that contains all positive elements of x, and a second(N) that contains the negative elements of x. The elements in new vectors are in the same order as in x.
I totally understand the conditional statement part, but for the loop part, I only worked this fragment out then don't know how to continue:
x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5];
P=[];
N=[];
a=length(x);
for k=1:a
if x>0
Someone please help! Thanks!

1 个评论

x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5];
P=[];
N=[];
for k=1:length(x)
if x(k)>=0
P(k)=x(k);
else if x(k)<0
N(k+2)=x(k)
end
end
end
N=circshift(N,-2)

请先登录,再进行评论。

类别

帮助中心File 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