# Elementwise operation with different dimensions of vectors

**URL:** https://discourse.julialang.org/t/elementwise-operation-with-different-dimensions-of-vectors/52543
**Category:** General Usage
**Created:** [December 28, 2020, 10:17pm UTC](https://discourse.julialang.org/t/elementwise-operation-with-different-dimensions-of-vectors/52543 "2020-12-28T22:17:16Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![rcesarpacheco](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rcesarpacheco/32/20585_2.png) [@rcesarpacheco](https://discourse.julialang.org/u/rcesarpacheco)
#### Post date: [December 28, 2020, 10:17pm UTC](https://discourse.julialang.org/t/elementwise-operation-with-different-dimensions-of-vectors/52543/1 "2020-12-28T22:17:16Z")

</div>

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:

```julia
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!

---

<div class="post-metadata">

### Author: ![OlivierHnt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/olivierhnt/32/6227_2.png) [@OlivierHnt](https://discourse.julialang.org/u/OlivierHnt)
#### Post date: [December 28, 2020, 11:29pm UTC](https://discourse.julialang.org/t/elementwise-operation-with-different-dimensions-of-vectors/52543/2 "2020-12-28T23:29:21Z")

</div>

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:

```nohighlight
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)`.
