# Elegant broadcasting over Matrix{Any} with different functions

**URL:** https://discourse.julialang.org/t/elegant-broadcasting-over-matrix-any-with-different-functions/64210
**Category:** New to Julia
**Created:** [July 7, 2021, 12:58pm UTC](https://discourse.julialang.org/t/elegant-broadcasting-over-matrix-any-with-different-functions/64210 "2021-07-07T12:58:01Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![Thomas](https://avatars.discourse-cdn.com/v4/letter/t/e36b37/32.png) [@Thomas](https://discourse.julialang.org/u/Thomas)
#### Post date: [July 7, 2021, 12:58pm UTC](https://discourse.julialang.org/t/elegant-broadcasting-over-matrix-any-with-different-functions/64210/1 "2021-07-07T12:58:01Z")

</div>

How do I apply function `f` over the diagonal and `g` over off-diagonal of a matrix, and more generally over indices `I` and `J`? Here `I` and `J` are subsets of product of the row and column index sets.

```julia
matrix = rand(3,3)
result = [i==j ? f(m[i,j]) : g(m[i,j]) for i in 1:size(matrix,1), j in 1:size(matrix,2)]

```

---

<div class="post-metadata">

### Author: ![Oscar\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oscar_smith/32/25343_2.png) [@Oscar\_Smith](https://discourse.julialang.org/u/Oscar_Smith)
#### Post date: [July 7, 2021, 1:24pm UTC](https://discourse.julialang.org/t/elegant-broadcasting-over-matrix-any-with-different-functions/64210/2 "2021-07-07T13:24:13Z")

</div>

I believe that is the cleanest way to express it.

---

<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: [July 7, 2021, 1:39pm UTC](https://discourse.julialang.org/t/elegant-broadcasting-over-matrix-any-with-different-functions/64210/3 "2021-07-07T13:39:54Z")

</div>

Maybe this one is more elegant (though probably slower)?

```julia
m = rand(3,3)
indices = CartesianIndices(m)
result = [I in diag(indices) ? f(m[I]) : g(m[I]) for I in indices]

```

Here’s another option using broadcasting:

```julia
m = rand(3,3)
I = diagind(m)
J = setdiff(LinearIndices(m), I)
result = similar(m)
result[I] .= f.(m[I])
result[J] .= g.(m[J])

```

and with the InvertedIndices.jl package you can replace `setdiff(LinearIndices(m), I)` with `Not(I)`.

(Edit: @Seif_Shebl made me realize I had inadvertently removed the broadcasting assignment.)

---

<div class="post-metadata">

### Author: ![Seif\_Shebl](https://avatars.discourse-cdn.com/v4/letter/s/eada6e/32.png) [@Seif\_Shebl](https://discourse.julialang.org/u/Seif_Shebl)
#### Post date: [July 8, 2021, 3:53am UTC](https://discourse.julialang.org/t/elegant-broadcasting-over-matrix-any-with-different-functions/64210/4 "2021-07-08T03:53:08Z")

</div>

Yes, you can use broadcasting too.

```julia
m = rand(3,3)
I = diagind(m)
r = g.(m)
r[I] .= f.(m[I])

```
