# Value Function - Scoping problem

**URL:** https://discourse.julialang.org/t/value-function-scoping-problem/20236
**Category:** New to Julia
**Tags:** economics
**Created:** [January 29, 2019, 4:18pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236 "2019-01-29T16:18:41Z")
**Posts on this page:** 11
**Page:** 1

<div class="post-metadata">

### Author: ![vatfancio](https://avatars.discourse-cdn.com/v4/letter/v/8e7dd6/32.png) [@vatfancio](https://discourse.julialang.org/u/vatfancio)
#### Post date: [January 29, 2019, 4:18pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/1 "2019-01-29T16:18:41Z")

</div>

Hi everyone. I am trying to create a simple Value Function Iteration routine for a basic econ. problem.  
I’m facing the common problem of global and local variable definition, but I don’t know how to correct in this case. Below is a simple version of the problem I am trying to solve:

```julia
agrid = 10
zgrid = 3

Pz = [0.11 0.85 0.04; 0.07 0.87 0.06; 0.03 0.85 0.12]

a = zeros(agrid, 1)
V = zeros(agrid, zgrid)
V_new = zeros(agrid, zgrid)

u = zeros(agrid)
erro = 100

while erro > 0.1
    for ia = 1:agrid
        for iz = 1:zgrid

            for ja = 1:agrid
                c = 0.02*a[ia] + exp(z[iz]) - a[ja]
                EV = transpose(Pz[iz,:])*V[ja,:]
                u[ja] = -1/c + 0.95*EV

            end
            Vmax, imax = findmax(u)
            V_new[ia,iz] = Vmax

        end
    end
erro = maximum(abs.(V_new - V))
V = V_new
end

```

The message I get is ‘UndefVarError: V not defined’. In this case, I don’t know how I can use ‘global definition variable’ or the ‘let’ operator to fix my problem.

Thanks!

---

<div class="post-metadata">

### Author: ![jbrea](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jbrea/32/3879_2.png) [@jbrea](https://discourse.julialang.org/u/jbrea)
#### Post date: [January 29, 2019, 5:13pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/2 "2019-01-29T17:13:08Z")

</div>

I get `ERROR: UndefVarError: z not defined`.  
If I define a `z`, and use `global V = V_new` in the last line I don’t get any error.

---

<div class="post-metadata">

### Author: ![dmolina](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dmolina/32/5246_2.png) [@dmolina](https://discourse.julialang.org/u/dmolina)
#### Post date: [January 29, 2019, 5:49pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/3 "2019-01-29T17:49:27Z")

</div>

It is a well-known behaviour, just put the code inside a function (not change is required), and it should be working.

---

<div class="post-metadata">

### Author: ![dmolina](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dmolina/32/5246_2.png) [@dmolina](https://discourse.julialang.org/u/dmolina)
#### Post date: [January 29, 2019, 5:52pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/4 "2019-01-29T17:52:15Z")

</div>

Outside functions, variables like V or z are global (for be defined out of any function or loop), so you need to put inside the loop the sentences like “global V” to use them.

---

<div class="post-metadata">

### Author: ![jlperla](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jlperla/32/34332_2.png) [@jlperla](https://discourse.julialang.org/u/jlperla)
#### Post date: [January 29, 2019, 6:31pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/5 "2019-01-29T18:31:04Z")

</div>

> [@dmolina](#):
>
> It is a well-known behaviour, just put the code inside a function (not change is required), and it should be working.

Yup. Use a function or stay in jupyter. For now, better to never use loops at top level scripts.

---

<div class="post-metadata">

### Author: ![vatfancio](https://avatars.discourse-cdn.com/v4/letter/v/8e7dd6/32.png) [@vatfancio](https://discourse.julialang.org/u/vatfancio)
#### Post date: [January 29, 2019, 6:47pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/6 "2019-01-29T18:47:31Z")

</div>

> [@vatfancio](#):
>
> Pz = [0.11 0.85 0.04; 0.07 0.87 0.06; 0.03 0.85 0.12]

Sorry, we could define z as `z = [-0.43 0 0.43]`, for instance. In this case, I do not get an error, but the code does not run.

---

<div class="post-metadata">

### Author: ![dmolina](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dmolina/32/5246_2.png) [@dmolina](https://discourse.julialang.org/u/dmolina)
#### Post date: [January 29, 2019, 6:59pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/7 "2019-01-29T18:59:27Z")

</div>

```nohighlight
    agrid = 10
    zgrid = 3

    Pz = [0.11 0.85 0.04; 0.07 0.87 0.06; 0.03 0.85 0.12]

    a = zeros(agrid, 1)
    # Your definition of z
    z = [-0.43 0 0.43]
    V = zeros(agrid, zgrid)
    V_new = zeros(agrid, zgrid)

    u = zeros(agrid)
    erro = 100

    while erro > 0.1
        for ia = 1:agrid
            for iz = 1:zgrid
                
                for ja = 1:agrid
                    c = 0.02*a[ia] + exp(z[iz]) - a[ja]
                    EV = transpose(Pz[iz,:])*V[ja,:]
                    u[ja] = -1/c + 0.95*EV
                end
                Vmax, imax = findmax(u)
                V_new[ia,iz] = Vmax
            end
        end
        erro = maximum(abs.(V_new - V))
        V = V_new
        println("Error is $erro\tV is $V")
    end # of loop

end # Of main

main()

```

Yes, because your code is not right, z was not defined anyway in your original code, and it was used in line 19. So, there is an error, and we cannot fix it, because it is not a problem with the language, it is a logic error. Using a function (or using Jupyter( avoid the problem to access variables.

I have update the code with the z values you say, and it is working (I cannot help you more because I have not idea what are you trying to calculate).

---

<div class="post-metadata">

### Author: ![yha](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yha/32/3502_2.png) [@yha](https://discourse.julialang.org/u/yha)
#### Post date: [January 29, 2019, 7:10pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/8 "2019-01-29T19:10:49Z")

</div>

> [@jlperla](#):
>
> For now, better to never use loops at top level scripts.

I think that’s a bit extreme. If the purpose of this piece of code if to compute `V`, it can say

```julia
V = let
   # ...
   # original code here
   # ...
   V
end

```

without requiring `global` annotations.

---

<div class="post-metadata">

### Author: ![vatfancio](https://avatars.discourse-cdn.com/v4/letter/v/8e7dd6/32.png) [@vatfancio](https://discourse.julialang.org/u/vatfancio)
#### Post date: [January 29, 2019, 8:54pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/9 "2019-01-29T20:54:48Z")

</div>

Perfect! Now, my second (and _main_) doubt is the following:  
We begin with `V = [0 0 0; ...]` and `V_new = [0 0 0; ...]`

In the first _while_ iteration we have `V_new = [-1.53 -1.0 -0.65; ...]`. Hence the error is 1.53 and V becomes `[-1.53 -1.0 -0.65; ...]`.

Since `1.53 > 0.1` we go to the second _while_ iteration but now with `V = [-1.53 -1.0 -0.65; ...]`

Hence, by the algorithm, we updated `V_new = [-2.53 -1.96 -1.57; ...]`.  
In this case, the _error_ should be `maximum(abs.(V_new - V)) = max(abs.([-2.53 -1.96 -1.57; ...]- [-1.53 -1.0 -0.65; ...]))`.

However, in the second _while_ iteration, the algorithm is updating `V` before computing the _error_, making `maximum(abs.(V_new - V)) = max(abs.([-2.53 -1.96 -1.57; ...]- [-2.53 -1.96 -1.57; ....])) = 0 > 0.1` and stoping the iteration.

_Matlab_ doesnt have this ‘behavior’ and dont know how to handle it in Julia.

I dont know if it is clear.  
Any way, you already contributed a lot. Thanks!

---

<div class="post-metadata">

### Author: ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)
#### Post date: [January 29, 2019, 9:01pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/10 "2019-01-29T21:01:38Z")

</div>

You’ve got a lot of code here, so it’s hard to be sure, but I would suspect that the problem is here:

```julia
V = V_new

```

in Matlab, this would _copy_ `V_new` and create a new vector called `V`. Any future changes to `V_new` would not affect `V`. In Julia, however, this just makes `V` a label for the _same_ vector as `V_new`, so any changes to `V_new` will be shared with `V`. This is actually how _all_ assignment operations in Julia work: Julia doesn’t silently copy things when you assign them or when you pass them to functions (unlike Matlab).

If you do want a copy, you can simply do: `V = copy(V_new)`.

Perhaps that will help you figure out what’s different in the results you’re seeing.

---

<div class="post-metadata">

### Author: ![vatfancio](https://avatars.discourse-cdn.com/v4/letter/v/8e7dd6/32.png) [@vatfancio](https://discourse.julialang.org/u/vatfancio)
#### Post date: [January 29, 2019, 9:23pm UTC](https://discourse.julialang.org/t/value-function-scoping-problem/20236/11 "2019-01-29T21:23:01Z")

</div>

It is precisely this point. I was skipping this detail in Julia.  
Thanks a lot.
