Count if a vector has at list one element greater than zero
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Enrico Gambini
am 5 Mär. 2021
Bearbeitet: Stephen23
am 6 Mär. 2021
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
Akzeptierte Antwort
Jorg Woehl
am 5 Mär. 2021
Bearbeitet: Jorg Woehl
am 6 Mär. 2021
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 Kommentare
Jorg Woehl
am 5 Mär. 2021
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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Naming Conventions finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!