1

I defined a function, let's say func(matrix_a, p, para) for simplicity. When I use the function in a for loop, error "matrix_a not defined" comes up. But if the function is called several times without a for loop, it works well.

The function is a bot special. According to different p, it will return a new matrix_a. When I call it, I do it in the following way:

matrix_a = func(matrix_a, p, para)

which is like the matrix_a is updated. It may be concatenated with a new row or just added some numbers in some elements.

To be more specific, it returns "matrix_a not defined" when

para = ones(4)
matrix_a = zeros(2, 2)
for i = 1: 4
    matrix_a = func(matrix_a, p, para[i])
end

It works well, when I test it:

para = ones(4)
matrix_a = zeros(2, 2)
i = 1
matrix_a = func(matrix_a, p, para[i])
i = 2
matrix_a = func(matrix_a, p, para[i])
i = 3
matrix_a = func(matrix_a, p, para[i])
i = 4
matrix_a = func(matrix_a, p, para[i])
Edward
  • 554
  • 8
  • 15
  • This is the famous global/local scope issue. You are trying to assign a global variable inside a local scope. You can add `global matrix_a` anywhere inside your loop to make `matrix_a` in the global scope to be inherited by the local scope of your `for` loop, *or* simply wrap your loop into a function that takes `matrix_a` as a parameter. https://docs.julialang.org/en/v1/manual/variables-and-scoping/index.html#Local-Scope-1 – hckr Apr 06 '19 at 21:12

1 Answers1

0

The reason is that you are using the global scope. IE you are writing code in the top level global environment

The three solutions are

Write it in a function

function main()
    para = ones(4)
    matrix_a = zeros(2, 2)
    for i = 1: 4
        matrix_a = func(matrix_a, p, para[i])
    end
end

main()

Write it inside a let block

let
    para = ones(4)
    matrix_a = zeros(2, 2)
    for i = 1: 4
        matrix_a = func(matrix_a, p, para[i])
    end
end

Treat the for loop, while loop as a function and label all outside variables as global variable

para = ones(4)
matrix_a = zeros(2, 2)
# treating the for loop like a function
for i = 1: 4
    global matrix_a = func(matrix_a, p, para[i])
end

Those are the solutions

Steven Siew
  • 843
  • 8
  • 11