I am trying to create two vectors out of one,x, where one will contain all the positive elements and the other all the negative elements.

1 次查看(过去 30 天)
%this program creates vectors N and P out of x
%N will contain negative elements and P the positive elements
x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5];
for k=length(x);
if x>=0
k=x
P(k)=k
else x<0
N(k)=k
end
end
P
N

采纳的回答

Star Strider
Star Strider 2015-4-2
Just use ‘logical indexing’:
x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5];
P = x(x >= 0);
N = x(x < 0);
  15 个评论

请先登录,再进行评论。

更多回答(1 个)

James Tursa
James Tursa 2015-4-2
编辑:James Tursa 2015-4-2
You are using k as a loop variable but only doing one iteration, k = 12. Maybe you want this result:
P = x(x>0);
N = x(x<0);
Or if you want them to retain their original spots, something like this
P = x;
P(~(x>0)) = 0;
N = x;
N(~(x<0)) = 0;
EDIT:
If you have to use loops, then change your looping index to the following:
for k=1:length(x)
And inside your loop, don't use x by itself in the test since that is the entire vector x. Instead, use the k'th element of x (i.e., use your k index). E.g.,
if x(k) >= 0
Finally, Don't change the value of k inside your loop! That will mess up the looping. So get rid of this line:
k=x
And then use x(k) on the right hand side of your assignments instead of k.
  3 个评论
Frank_m
Frank_m 2015-4-2
It seemed to solve the problem, P is now a vector but vector N is not coming out.
%this program creates vectors N and P out of x
%N will contain negative elements and P the positive elements
x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5];
for k=length(x);
if x(k)>=0
P = x(x>0);
else x(k)<0
N=x(x<=0)
end
end
P
N
P =
6.2000 11.0000 8.1000 3.0000 3.0000 2.5000
N =
1 2 3 4 0 0 0 0 0 0 0 12
James Tursa
James Tursa 2015-4-2
编辑:James Tursa 2015-4-2
LOL. Well, if you just change your else statement to this (i.e., drop the x(k) < 0 part) you will have something:
else
However, your "loop" is basically solving the entire problem in a vectorized manner at each iteration! So, this is not really in the spirit of the looping requirement.
I would take a look at Star Strider's comment since he has it basically laid out for you in detail (although it looks like he needs to fix the else line as well).

请先登录,再进行评论。

类别

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