MATLAB: 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.

loopsvector

%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

Best Answer

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);