Is A==0 really better than ~A?

This is not strictly an answer but rather my contribution to the discussion

I used the profiler to investigate a slightly-modified version of your code:

N_arr = 200:400:3800; %// for medium to large sized input array

for k1 = 1:numel(N_arr)

    A = randi(1,N_arr(k1));
    clear A

    A = randi(1,N_arr(k1));
    clear A   


I used the following profiler flags (as per UndocumentedMatlab’s series of posts about Profiler):


And here’s an excerpt from the profiler results (link to the larger image):
Profiler output

It seems that the == variant allocates a tiny bit of additional memory that allows it to work its magic….

Regarding your question 2: Before removing the keeping of timeall, I tried plotting the same charts you did in Excel. I didn’t observe the behavior you mentioned for N = 320. I suspect this may have something to do with the additional wrappers (i.e. function handles) you’re using in your code.

I thought I’d attach the available documentation for the discussed functions for quick reference.

The documentation for ~ (\MATLAB\R20???\toolbox\matlab\ops\not.m):

%~   Logical NOT.
%   ~A performs a logical NOT of input array A, and returns an array
%   containing elements set to either logical 1 (TRUE) or logical 0 (FALSE).
%   An element of the output array is set to 1 if A contains a zero value
%   element at that same array location.  Otherwise, that element is set to
%   0.
%   B = NOT(A) is called for the syntax '~A' when A is an object.
%   ~ can also be used to ignore input arguments in a function definition,
%   and output arguments in a function call.  See "help punct"

%   Copyright 1984-2005 The MathWorks, Inc.

The documentation for == (\MATLAB\R20???\toolbox\matlab\ops\eq.m):

%==  Equal.
%   A == B does element by element comparisons between A and B
%   and returns a matrix of the same size with elements set to logical 1
%   where the relation is true and elements set to logical 0 where it is
%   not.  A and B must have the same dimensions unless one is a
%   scalar. A scalar can be compared with any size array.
%   C = EQ(A,B) is called for the syntax 'A == B' when A or B is an
%   object.

%   Copyright 1984-2005 The MathWorks, Inc.

Leave a Comment