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 日

0 投票

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 件のコメント

Enrico Gambini
Enrico Gambini 2021 年 3 月 5 日
Thank you for the answer, but in my case i don't want to have a count of all the vector elements which are greater than zero. I'd like to count if and only if at least one element of the vector is greater than zero.
For example if i have the vector v=[0,20,10,0,100] there's at least one element greater than zero and so i count.
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 件)

カテゴリ

製品

リリース

R2020b

質問済み:

2021 年 3 月 5 日

編集済み:

2021 年 3 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by