Matlab and any, difficulties in understanding
Question
I can't understand what this code does:
if any(scale==0)
loglik = -inf;
I have to translate it into C++ with the Armadillo library, that does not have an any
function so I was wondering how to do it.
I've read the matlab manuals, but it is still confusing. I've then tried with this test case:
if any([*]==0)
1
else
0
end
using as * those values (and many more):
[0 0;0 0]
[1 0;0 0]
[1 0;1 0]
[1 0;0 1]
[1 1;1 1]
but I am still confused and results are dark.. any explanation please?
Solution
Matlab (and Armadillo) represent booleans as 0
for false
and 1
(or really anything that's not 0
) for true
. They both define an ==
operator over matrices/vectors that does component-wise comparisons and outputs a matrix of booleans. any
is taking in that matrix of booleans and checking if any are non-zero.
Armadillo does not appear to have any
, but it does provide find
which can be used to implement any
:
!find(X, 1).is_empty()
is equivalent (albeit possibly slower): it constructs a vector of at most one non-zero elements (documentation for find). If it's empty, then there are no non-zero elements, so any
would return false.
OTHER TIPS
As of version 3.910, Armadillo has the any() function.