How to define a numerical value in Julia?

I keep getting the below error:
LoadError: UndefVarError: n1 not defined

for my below code:

n1 = 0;
for i in 1:m[1], j in 1:m[2]
        n1 += 1;
        A[n1,:] = [X0[i,j] Y0[i,j] E0[i,j]];
end

Hasn’t my “n1=0;” defined n1? Anyone has any clue? Thanks!

It is a scoping problem. Read this: Scope of loops · JuliaNotes.jl

1 Like

Many thanks. So what is the best fix? The below? Coming from Matlab, I think this is so weird!

n1 = 0;
for i in 1:m[1], j in 1:m[2]
        global n1;
        n1 += 1;
        A[n1,:] = [X0[i,j] Y0[i,j] E0[i,j]];
end

The best solution is to write everything into functions:

julia> function f()
           n1 = 0
           for i in 1:10
               n1 += 1
           end
           n1
       end
f (generic function with 2 methods)

julia> f()
10

Then pass A, m, X0, Y0, E0, as parameters to that function. That not only avoids the scoping problem, but is fundamental for the performance of the code. See: Performance Tips · The Julia Language

(not using global variables is the first tip and the most fundamental rule that is needed to start getting Julia code to run fast)

5 Likes

ps: there are other Julia anti-patterns in that code. If you provide an actual running example, with the expected output, we can give you better advice in general.

For example:

A[n1,:] = [X0[i,j] Y0[i,j] E0[i,j]];

This is allocating a new (1,3) matrix on the right, which can be improved just by using a tuple () instead of a vector [], but also you are running over the last dimension first, which is slower, because Julia is column-major. I’m not sure if performance is important in this specific case, but on the long run it is good to get the feeling of these ideas.

4 Likes

Maybe pertinent to note that this comment also applies to matlab code.

1 Like