Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why any('') returns logical 0 while all('') returns logical 1?

Tags:

matlab

I just found the statement any('') returns a logical 0, while the statement all('') returns a logical 1.

If the function any does not think the empty string ('') as nonzero, the function all should do the same, but from the result, the function all seems to think the empty string ('') as nonzero.

BTW, the similar thing happens where any(NaN) returns logical 0 while all(NaN) returns logical 1.

Is it a MATLAB bug?

Here is the version information of the MATLAB I am using.
MATLAB Version: 9.1.0.441655 (R2016b)
MATLAB License Number: DEMO

like image 221
Ray Chen Avatar asked Feb 04 '23 22:02

Ray Chen


1 Answers

According to the Documentation
definition of any:

any(x) ...determines if any element is a nonzero number or logical 1 (true)

In practice, any is a natural extension of the logical OR operator.

If A is an empty 0-by-0 matrix, any(A) returns logical 0 (false).

and definition of all:

all(x) ...determines if the elements are all nonzero or logical 1 (true)

In practice, all is a natural extension of the logical AND operator.

If A is an empty 0-by-0 matrix, then all(A) returns logical 1 (true).

We can implement both functions:

function out = Any(V)
    out = false;
    for k = 1:numel(V)
        out = out || (~isnan(V(k)) && V(k) ~= 0);
    end
end

function out = All(V)
    out = true;
    for k = 1:numel(V)
        out = out && (V(k) ~= 0);
    end
end

Explanation:

-In any we assume that all elements are not nonzero [so all are zeros] and we want to prove that the assumption is wrong so we provide an initial value of false.
-Because any is a natural extension of the logical OR operator we use ||
-Because we should check for nonzero numbers we use V(k) ~= 0
-Because we should check for nonzeros numbers and NaN is Not a Number we use ~isnan(V(k)).

-In all we assume that all elements are nonzero [so all are ones] and we want to prove that the assumption is wrong so we provide an initial value of true
-Because all is a natural extension of the logical AND operator we use &&
-Because we should check for nonzeros we use V(k) ~= 0
-Because the definition of all doesn't force that nonzero elements to be numbers we don't use ~isnan(V(k))

like image 170
rahnema1 Avatar answered Feb 08 '23 16:02

rahnema1