# Efficiently creating array of dimension 3 from element-wise matrix addition

**URL:** https://discourse.julialang.org/t/efficiently-creating-array-of-dimension-3-from-element-wise-matrix-addition/75646
**Category:** General Usage
**Tags:** arrays
**Created:** [February 2, 2022, 11:21am UTC](https://discourse.julialang.org/t/efficiently-creating-array-of-dimension-3-from-element-wise-matrix-addition/75646 "2022-02-02T11:21:39Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Eriklw](https://avatars.discourse-cdn.com/v4/letter/e/ea666f/32.png) [@Eriklw](https://discourse.julialang.org/u/Eriklw)
#### Post date: [February 2, 2022, 11:21am UTC](https://discourse.julialang.org/t/efficiently-creating-array-of-dimension-3-from-element-wise-matrix-addition/75646/1 "2022-02-02T11:21:39Z")

</div>

I have to perfrom an operation, in which I create an array with dimension 3 from two matrices in the following way:

C[i,j,k] = A[i,j] + B[j,k]

I can do this of course with a loop but this seems by far not the best way to compute this. Is there a more efficient way?

---

<div class="post-metadata">

### Author: ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)
#### Post date: [February 2, 2022, 11:35am UTC](https://discourse.julialang.org/t/efficiently-creating-array-of-dimension-3-from-element-wise-matrix-addition/75646/2 "2022-02-02T11:35:44Z")

</div>

Loops are not inefficient, on the contrary any efficient solution is probably equivalent to a loop under the hood!

You could write this directly with an array comprehension:

```julia
A = rand(3,4)
B = rand(4,5)

C = [A[i,j] + B[j,k] for i in axes(A,1),
                         j in axes(A,2),
                         k in axes(B,2)]

```

but this is a perfect job for an Einstein summation macro, for example with Tullio:

```julia
using Tullio

@tullio C[i,j,k] := A[i,j] + B[j,k]

```

Hard to make this more readable, and it should be very fast 🙂

---

<div class="post-metadata">

### Author: ![rafael.guerra](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rafael.guerra/32/216610_2.png) [@rafael.guerra](https://discourse.julialang.org/u/rafael.guerra)
#### Post date: [February 2, 2022, 12:14pm UTC](https://discourse.julialang.org/t/efficiently-creating-array-of-dimension-3-from-element-wise-matrix-addition/75646/3 "2022-02-02T12:14:25Z")

</div>

FWIW, here is an alternative using TensorCast, which should be more lightweight to load and to run the first time than Tullio:

```julia
using TensorCast
@cast C[i,j,k] := A[i,j] + B[j,k]

```
