How to separate all negative and all positive values of a vector?

Illustration
Sergey Dukman - 2023-07-08T12:45:55+00:00
Question: How to separate all negative and all positive values of a vector?

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:')

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

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

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!