MATLAB: How to separate all negative and all positive values of a vector

vectors in matlab

Hello, I baffled by one task in Matlab, namely I need to create two vectors that contains all positive and all negative values of an initial vector. I would like to get a general answer to my question. Here is my script (unfinished): for i=1:numel(x) if x(i) > 0 & x(i)==0 P(i)=????????(all positives) end end disp('The postive vector is:')
Sergey

Best Answer

You don't need a loop, because logical indexing is much simpler and faster:
>> X = [1,2,-3,-4,5,-6,7,-8,9];
>> idx = X<0; % create logical index
>> neg = X(idx)
neg =
-3 -4 -6 -8
>> pos = X(~idx)
pos =
1 2 5 7 9