Skip to content

any

Determine if any element is non-zero

b = any(A)

  • When A is a scalar, b is logical 1 if A is nonzero, and logical 0 if otherwise.
  • When A is a vector, b is logical 1 if any element of A is non-zero, and logical 0 if otherwise.
  • When ndims(A) >= 2, an element of b is assigned logical 1 if any element of corresponding vector of A along the first non-singleton dimension is non-zero, and logical 0 if otherwise.
  • any(A) collapses the first non-singleton dimension of A. That means, if size(A) is [s1 s2, ..., sN], then size(b) is equal to [1 s2, s3, ..., sN].
  • For example, b(1,1,1) == 1 if A(:,1,1) has a non-zero element.

b = any(A, dim)

  • dim should be a positive integer.
  • If dim > ndims(A), then it gives the same result as b = any(A).
  • If the dim-th dimension of A is non-singleton, an element of b is assigned logical 1 if any element of the corresponding vector of A along the dim-th dimension is non-zero, and logical 0 if otherwise.

Example 1: Check if vectors along the 3rd dimension of a random matrix a has any non-zero elements.

a=randi(4,3,3,3)-2
any(a,3)
a(:, :, 1) =

-1.000   0.000  -1.000
 2.000   2.000   0.000
 0.000  -1.000  -1.000

a(:, :, 2) =

 1.000   0.000  -1.000
 1.000   2.000   1.000
 0.000   1.000   2.000

a(:, :, 3) =

 0.000   0.000   1.000
-1.000   1.000   1.000
 1.000   0.000   2.000

ans =
 1   0   1
 1   1   1
 1   1   1