Efficient way of comparing two matrices

Hello, this question might seem very naive. But what is the best way of doing a logical comparison of two matrices. Consider the following MWE:

function compare(N)
    for n=1:N
        X=rand([0,1],4,4)
        Y=rand([0,1],4,4)
        if X != Y
            println("These matrices are different")
        end
    end
end

What about this doesn’t work? That all looks fine to me.

In principle, everything works.

I was just wondering whether


X != Y

is the most efficient way to do the logical comparison of the matrices.

It almost certainly is, and if someone finds something faster and reports it, a pull request will be made in Julia to make that faster way be the way X!=Y is computed.

1 Like

If you check (eg with @edit) you will find that it ultimately dispatches to (==)(A::AbstractArray, B::AbstractArray) which is written efficiently (in the sense that it will return early if it finds a discrepancy).

Generally, if you are concerned about efficiency, it is best to just learn about the relevant tools — the performance tips is a good starting point for efficiency of compiled code, while for algorithmic efficiency you should just learn to understand Julia code.

3 Likes