Reputation: 1
Title says it all. I Know what both of these functions do individually, but combining them is proving difficult.
Upvotes: 0
Views: 62
Reputation: 104514
Collecting all of the answers from the comments, you can do it in a variety of ways:
numel(find(a == min(0)))
(à la Try Hard). The min(0)
is rather superfluous as you can simply do a == 0
, but because you are required to use min
, we need that there. The general case is (à la Divakar) numel(find(a == min(abs(a))));
. This is assuming that the minimum of a
is zero. Essentially, this finds all locations that are zero, and determining how many of these elements are zero is done with numel
.
I personally would not use find
and min
. A.Donda suggests to use sum
, which is certainly more elegant... so do: sum(a == 0)
. a == 0
produces a logical vector where 1
at a position means that the corresponding element at this position in a
is 0 and 0
otherwise. We sum up all of the cases where we have 1
, which produces how many zero values there are.
This was one I came up with: numel(a) - nnz(a)
. This comes from the fact that we can decompose the total number of elements in a vector to be the number of zero elements, added with the total of non-zero elements, or nz(a) + nnz(a) = numel(a)
, and so nz(a) = numel(a) - nnz(a)
. There is a function in MATLAB called nnz
, which counts how many non-zero elements there are in a vector or matrix. Therefore, you can count how many zero elements there are by numel(a) - nnz(a)
. It's not as elegant as sum(a == 0)
, but it's certainly another way to achieve what you want.
Upvotes: 1