Count if a vector has at list one element greater than zero

조회 수: 42 (최근 30일)
Enrico Gambini
Enrico Gambini 2021년 3월 5일
편집: Stephen23 2021년 3월 6일
Hello everyone, I'm looking for a way to update a count if a vector has at least one element greater than zero.
I mean for example:
count=0;
v=rand(100,1);
%check if v has at least one element greater than zero, if yes
count=count+1;
Thank you
  댓글 수: 1
Enrico Gambini
Enrico Gambini 2021년 3월 5일
I think i got a part of the answer
if(any(v)) %returns true if any of the elements of v is nonzero
count=count+1;
end

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

채택된 답변

Jorg Woehl
Jorg Woehl 2021년 3월 5일
편집: Jorg Woehl 2021년 3월 6일
count = sum(v>0)
The expression v>0 creates a logical array of 1s and 0s, with a 1 for every element of v that is greater than zero. Summing all values in the logical array therefore gives the total number of elements greater than zero.
(By the way, the rand function only generates positive numbers between 0 and 1, so to create random numbers between -1 and 1, you would use 1-2*rand.)
  댓글 수: 3
Jorg Woehl
Jorg Woehl 2021년 3월 5일
I see - in this case, using the any function like you suggested would be the way to go. Test if at least one element of v is greater than zero and then increase the count variable accordingly:
if (any(v>0)) % returns true if at least one element of v is greater than zero
count=count+1;
end
Stephen23
Stephen23 2021년 3월 6일
편집: Stephen23 2021년 3월 6일
Simpler:
count = count + any(v>0);

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by