A function that counts the number of zeros in a vector

3 次查看(过去 30 天)
D = ones(1,20);
for i = 1:20;
if mod(i,2) == 0;
D(i) = 0;
end
end
---------
D = [ 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0]
and I need A function that counts the number of zeros in a vector I know there are 10 zeros but how to earn? I found only this but is not enough.
sum(find(D==0)/11) = 10

回答(3 个)

Stephen23
Stephen23 2021-10-12
编辑:Stephen23 2021-10-12
D = [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0];
nnz(D==0)
ans = 10

Dave B
Dave B 2021-10-12
you were pretty close, you just didn't need the find, or the /11
D = [ 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0]
D = 1×20
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
sum(D==0)
ans = 10

Jan
Jan 2021-10-12
Beside
sum(D == 0)
nnz(D)
This would be working also, if the elements are 0 or 1 only:
numel(D) - sum(D)

类别

Help CenterFile Exchange 中查找有关 Digital and Analog Filters 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by