tags:

views:

164

answers:

2

I'm testing an arbitrarily-large, arbitrarily-dimensioned array of logicals, and I'd like to find out if any one or more of them are true. any() only works on a single dimension at a time, as does sum(). I know that I could test the number of dimensions and repeat any() until I get a single answer, but I'd like a quicker, and frankly, more-elegant, approach.

Ideas?

I'm running 2009a (R17, in the old parlance, I think).

Thanks.

+9  A: 

If your data is in a matrix A, try this:

anyAreTrue = any(A(:));

EDIT: To explain a bit more for anyone not familiar with the syntax, A(:) uses the colon operator to take the entire contents of the array A, no matter what the dimensions, and reshape them into a single column vector (of size numel(A)-by-1). Only one call to ANY is needed to operate on the resulting column vector.

gnovice
Of course. Thanks.
Marc
+2  A: 

As pointed out, the correct solution is to reshape the result into a vector. Then any will give the desired result. Thus,

any(A(:))

gives the global result, true if any of numel(A) elements were true. You could also have used

any(reshape(A,[],1))

which uses the reshape operator explicitly. If you don't wish to do the extra step of converting your matrices into vectors to apply any, then another approach is to write a function of your own. For example, here is a function that would do it for you:

======================

function result = myany(A)

% determines if any element at all in A was non-zero

result = any(A(:));

======================

Save this as an m-file on your search path. The beauty of MATLAB (true for any programming language) is it is fully extensible. If there is some capability that you wish it had, just write a little idiom that does it. If you do this often enough, you will have customized the environment to fit your needs.

woodchips

related questions