필터 지우기
필터 지우기

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

조회 수: 80 (최근 30일)
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

채택된 답변

Stephen23
Stephen23 2015년 9월 23일
편집: Stephen23 2015년 9월 23일
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
  댓글 수: 5
Walter Roberson
Walter Roberson 2023년 3월 20일
Do we understand correctly that there should be 11 different outputs?
  1. element in first vector and second vector are both positive
  2. element in first vector is positive, element in second vector is zero
  3. element in first vector is positive, element in second vector is negative
  4. element in first vector is zero, element in second vector is positive
  5. element in first vector is zero, element in second vector is zero
  6. element in first vector is zero, element in second vector is negative
  7. element in first vector is negative, element in second vector is positive
  8. element in first vector is negative, element in second vector is zero
  9. element in first vector is negative, element in second vector is negative
  10. element exists in first vector but you have run out of elements in the second vector
  11. element exists in second vector but you have run out of elements in the first vector
Or should the cases where you have run out of elements in one of the vectors each be split into the negative / zero /positive, leading to a total of 15 different cases?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

RAM MANOHAR
RAM MANOHAR 2019년 7월 23일
I have used for , if --else loops but i have got positive and 0 in place of negative.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by