# Element by element wise multiplication and addition/subtraction of 3d matrices

**URL:** <https://discourse.julialang.org/t/element-by-element-wise-multiplication-and-addition-subtraction-of-3d-matrices/100178>\
**Category:** Numerics\
**Tags:** question\
**Created:** [June 11, 2023, 10:32am UTC](https://discourse.julialang.org/t/element-by-element-wise-multiplication-and-addition-subtraction-of-3d-matrices/100178 "2023-06-11T10:32:15Z")\
**Posts on this page:** 1\
**Showing post:** 13

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [June 14, 2023, 6:48pm UTC](https://discourse.julialang.org/t/element-by-element-wise-multiplication-and-addition-subtraction-of-3d-matrices/100178/13 "2023-06-14T18:48:37Z")

</div>

> [@smac](#):
>
> ```julia
> function matrRand2(nx,nG)
> 
> iLen = nx-nG*2
> 
> matrXYZ = zeros(Float64,iLen,iLen,iLen)
> matrXYZ .= rand(iLen,iLen,iLen)
> 
> return matrXYZ
> end
> 
> ```

If you are calling this function repeatedly, you probably need to preallocate `matrXYZ` to avoid having to create at every time, and you can write it like this:

```julia
function matRand2!(matrXYZ,nx,nG)
    iLen = nx - nG*2
    for i in 1:iLen, j in 1:iLen, k in 1:iLen
        matrXYZ[i,j,k] = rand()
    end
    return matrXYZ
end

```

and then you have to allocate `matrXYZ` up in the program and pass it here as a parameter.

But, please, read this before posting your questions, because otherwise it is hard to help:

> [@Please read: make it easier to help you](https://discourse.julialang.org/t/please-read-make-it-easier-to-help-you/14757):
>
> Welcome to the Julia Discourse! We are enthusiastic about helping Julia programmers, both beginner and experienced. This public service announcement (PSA) outlines best practices when asking for help. Following these points makes it easier for us to help you and more likely you’ll get a prompt, useful answer. Keywords are highlighted to make it easier to refer to specific points. Choose a descriptive title that captures the key part of your question, eg “plots with multiple axes” instead of …

---

_[View the full topic](https://discourse.julialang.org/t/element-by-element-wise-multiplication-and-addition-subtraction-of-3d-matrices/100178)._
