# Multiplying Matrix inside a loop

Hello, i try to write an alorithm where the Matrix is iterated ofer a table value. In each step the Matrix should be multiplyed with the Matrix before. I tried severl approches but i didn’t find something which is working. Anybody have an idea, how i can do it?

So at the End i want

``````M_final = M_display_1*  M_display_2 * M_display_3
``````

My code now working:

``````using LinearAlgebra
using SymbolicUtils
using Plots

@syms a_n b_n c_n d_n
@syms a b c d
@syms a1 b1 c1 d1
@syms a2 b2 c2 d2
@syms a3 b3 c3 d3

values_table = [
(a1, b1, c1, d1),
(a2, b2, c2, d2),
(a3, b3, c3, d3),
]

M_n( a_n, b_n, c_n, d_n ) = [   a_n  0   0    0;
0    b_n 0    0;
0    0   c_n  0;
0    0   0    d_n ]

M_final = Matrix(I, 4, 4)

for (i, row) in enumerate(values_table )
a, b, c, d = row

M_display= M_n(a, b, c, d  )

global M_final *= M_display

end
``````

Hi!

You forgot to define the `M_final` variable. Try adding this before the loop

``````M_final = Matrix(I, 4, 4)
``````

1 Like

Hello, thank you for your answer. I did this before. But i get always this message:

`````` Exception has occurred: UndefVarError

UndefVarError: `M_final` not defined
``````

When i define it inside the loop than it is working but result is wrong.

Hi there, try defining `M_final` outside the loop and using it in the loop with the `global` keyword (Control Flow · The Julia Language). Alternatively the loop with the definition of `M_final` could be put in a function.

1 Like

Thank you very much. Global solved it for me.

I would not recommend `global`. Put the code in a function instead.

Hello, can you please describe why i should do it in funcitons?

Can’t speak for DNF of course but:

(or hundreds of other pieces all across the internet if you search for them)

1 Like

Indeed, globals are not good, and for Julia they are particularly bad, as they also harm performance. The performance in Julia is built around type stability and compiling functions. Avoiding working with globals in global scope is the number one performance tip in the manual: Performance Tips · The Julia Language

Thank you for this helpful informations. But i run in an issue that i have no idea how to do it in function. at the end i have to call the function again and have to iterate over the function to get my result.