Display only positive values

조회 수: 36 (최근 30일)
Kat
Kat 2019년 9월 28일
댓글: Star Strider 2019년 9월 28일
Hello. I am trying to display only the positive values of a vector by using the find function to find where the negative values are first and then displaying only the positive values. I have tried using i = find(vector<0) but I don't know how to only delete the negative values using the find function to display only the positive values. Thanks.

채택된 답변

Star Strider
Star Strider 2019년 9월 28일
Yolu can simply use logical indexing for this, find is not absolutely necessary.
However, if you want to use find, assign its output to a variable:
idx = find(vector>0);
PosVals = vector(idx);
Testing for the negative values and then eliminating them requires an extra step:
idx = find(vector<0);
posidx = setdiff((1:numel(vector)), idx);
PosVals = vector(posidx)
Experiment to get different results.
  댓글 수: 2
Kat
Kat 2019년 9월 28일
Is there a way to do that without using any other built-in functions? Thanks.
Star Strider
Star Strider 2019년 9월 28일
Yes. Just test for positive values and return those indices. If you want to test for negative velues, use logical indexing and the logical negation (~) operator:
Lneg = vector < 0; % Logical Vector Of Elements < 0
Lpos = ~Lneg; % Logical Vector Of Elements >= 0
Then use find with those if you want to.

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

추가 답변 (0개)

태그

Community Treasure Hunt

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

Start Hunting!

Translated by