Amro
July 22, 2022, 4:20pm
1
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?
#run.jl
function update(Record,iter)
Record += Record*iter;
end
# main code
include("run.jl");
select = true;
if select == true
Record = [1,2;3,4];
end
iter=0;
for _ in 1:100
iter += 1;
update(Record,iter)
end
DNF
July 22, 2022, 5:03pm
2
The matrix Record
is not updated, because you are not updating it.
Amro:
Record += Record*iter;
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
Amro
July 22, 2022, 5:55pm
3
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
end
DNF
July 22, 2022, 6:03pm
4
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
with
Record .*= float(iter + 50)^100
The use of float
is to avoid integer overflow.
Amro
July 22, 2022, 6:11pm
5
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 ;
end
DNF
July 22, 2022, 7:18pm
8
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.
Amro
July 22, 2022, 7:30pm
9
Lol, thank you. I really appreciate your help during vacation.
acxz
July 23, 2022, 2:29am
10
For a solution to a similar problem to this see the following comment; How to build this sparsematrix in Julia - #9 by acxz