How to separate all negative and all positive values of a vector?
57 次查看(过去 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
0 个评论
采纳的回答
Stephen23
2015-9-23
编辑:Stephen23
2015-9-23
>> 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
2023-3-20
Do we understand correctly that there should be 11 different outputs?
- element in first vector and second vector are both positive
- element in first vector is positive, element in second vector is zero
- element in first vector is positive, element in second vector is negative
- element in first vector is zero, element in second vector is positive
- element in first vector is zero, element in second vector is zero
- element in first vector is zero, element in second vector is negative
- element in first vector is negative, element in second vector is positive
- element in first vector is negative, element in second vector is zero
- element in first vector is negative, element in second vector is negative
- element exists in first vector but you have run out of elements in the second vector
- 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
2019-7-23
I have used for , if --else loops but i have got positive and 0 in place of negative.
2 个评论
Narendra Kintali
2022-9-23
Hi Ram,
I even got zeros in the place of negative numbers.
How did you fix your code.
Walter Roberson
2022-9-23
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!