What is the best way to update matrix in callable function?

I have a file called “run.jl” which has a function “update”. I have a main function which create matrix “Record”, which needs to be updated in a for loop. However, the matrix is not updated. What is the best way to update it with defining it as global variable?

function update(Record,iter)
Record += Record*iter;
# main code
select = true;
if select == true
  Record = [1,2;3,4];
for _ in 1:100
iter += 1;

The matrix Record is not updated, because you are not updating it.

does not update Record, but instead creates a new matrix, which has a value equal to Record + Record*iter.

If you want to update it you must do it in-place, which you can achieve with .= (notice the dot):

Record .+= Record .* iter

But you could also write this as

Record .*= (1 + iter)
1 Like

I got it, thank you very much!
Given that:

Record = [1,2;3,4];

which method below is faster (In terms of performance):

for _ in 1:100
Record .= Record*iter + Record*50 ;           # Method-1
Record[:] = Record[:]*iter + Record[:]*50;    # Method-2

Neither of them is good. The last line is definitely bad, but also in the first one you forget dots, and do unnecessary operations.

should rather be

Record .= Record .* iter .+ Record .* 50

Make sure all dots are there.

But it’s better to do

Record .*= (iter + 50) 

But you can replace the whole loop


Record .*= float(iter + 50)^100

The use of float is to avoid integer overflow.

Thank you!
Actually, I tried to shorten the scheme. The original is:

Record = [1,2;3,4];
SS = [3,4;5,6];
iter = 0;
for _ in 1:100
iter += 1;
Record .= Record .* iter .+ SS .* 50 ; 

What is iter?

I’ve corrected.

That’s a bit harder to simplify, at least for my vacation brain😎

But at least you can do

for iter in 1:100

instead of iter += 1 inside the loop body.

Lol, thank you. I really appreciate your help during vacation.

For a solution to a similar problem to this see the following comment; How to build this sparsematrix in Julia - #9 by acxz