I am starting to write some codes in Julia and I have some doubts about elementwise operations.
Imagine that I have two matrices, A and B:
A= randn(3,3,3);
B = rand(3,3);
When I do something like A .==B
what the compiler is doing is comparing
A[:,:1] .== B and A[:,:,2] .==B and A[:,:,3] .== B
and returning a boolean matrix (3,3,3) with the result? Is this correct?
The same applies for elementwise multiplication?
Is this a bad practice or leads to slow performance ? Is there a better way of doing this?
Thanks!
What do you mean? It is definitely intended to behave this way and meant to be used
Do you mean that you do not want the whole array? In which case:
A = randn(3,3,3)
B = A[:,:,1]
compare_array(A, B) = A .== B
compare_bool(A, B) = all(k -> view(A, :, :, k) == B, axes(A, 3))
using BenchmarkTools
@btime compare_array($A, $B);
@btime compare_bool($A, $B);
compare_array
is your function. As you said it returns the whole array and tells you precisely if there was a match or not and where
compare_bool
performs the same tests but returns true or false such that all(compare_array(A, B)) == compare_bool(A, B)
.