0
votes

What is the most elegant way to reduce elementwise-conditions in multidimensional-arrays to one logical variable in Matlab? I need this for a big project with a lot of if conditions and assertions. In the Matlab documentation about logical arrays and find array elements there is no satifying solution for this problem.

For example, a logical variable myBool is true iff there are two ones at the same position in the matrices A and B:

A = [0,1;0,0]
B = [0,1;1,0]

My preferred solution so far is:

myBool = any(A(:)==1 & B(:)==1)

But it doesn't look like the shortest solution and it doesn't work with array indexing.

A shorter but not very readable solution:

myBool = any(A(B==1))

The biggest problem is that for higher dimensional arrays the functions like nnz() only reduce the order by one dimension without the colon (:), but with the colon it is not possible to index a part of the array...

1
From your example it would appear that your "preferred solution" is perfectly adequate. But you say it's not. Can you ellaborate why? What do you mean that it doesn't work with array indexing?Luis Mendo
I thought it would be possible to circumvent the colon operator somehow. The solution by @Dylan Richard Muir solves the indexing problem.JaBe

1 Answers

1
votes

Firstly, if you use matrices of class logical, then you don't need to test for equality to 1.

Indexing aside, the best approach would be:

bFlag = any(A(:) & B(:));

If you need indexing, you have two options. You can use a small vectorising anonymous function:

fhVec = @(T)(T(:));
bFlag = any(fhVec(A(rowIndices, colIndices) & B(rowIndices, colIndices)));

alternatively, you can use linear indexing:

vnLinearIndices = sub2ind(size(A), rowIndices, colIndices);
bFlag = any(A(vnLinearIndices) & B(vnLinearIndices));