## Same Functions but Return Different Values

### Ivy Zhong (view profile)

on 28 Jan 2018 at 22:06
Latest activity Edited by John D'Errico

### John D'Errico (view profile)

on 28 Jan 2018 at 22:28

I have two identical functions but they return completely different values. Function v() is from my script. Function w() is what I copy and pasted in the command window using the v()'s formula. The output value of v() is wrong. Does anyone have any idea where I might have done wrong?

### John D'Errico (view profile)

on 28 Jan 2018 at 22:16
Edited by John D'Errico

### John D'Errico (view profile)

on 28 Jan 2018 at 22:28

When you create a function handle, any constants in there are encapsulated, frozen in place at the values they took on when the function handle was created.

For example:

```a = 17;
F1 = @(x) x + a
```
```a = pi;
F2 = @(x) x + a
```

So, identically the same function. Or so it seems. But are they? I changed the value of a between setting up the two functions. What does MATLAB say?

```F1(0)
ans =
17
```
```F2(0)
ans =
3.1416
```

So F1 and F2 are NOT truly the same. I will claim quite confidently that you did something equivalent when you created v and w.

How can we figure out what changed between the two function handles?

```S1 = functions(F1)
S1 =
struct with fields:
```
```              function: '@(x)x+a'
type: 'anonymous'
file: ''
workspace: {[1×1 struct]}
within_file_path: '__base_function'```
```S1.workspace{1}
ans =
struct with fields:
```
`      a: 17`
```S2 = functions(F2)
S2 =
struct with fields:
```
```              function: '@(x)x+a'
type: 'anonymous'
file: ''
workspace: {[1×1 struct]}
within_file_path: '__base_function'
S2.workspace{1}
ans =
struct with fields:```
`      a: 3.1416`

So we see that a is not the same between F1 and F2, even though F1 and F2 look identically alike.

Anyway, be very careful when you are creating functions that involve vodka. Too much, and your computer might get drunk. I don't think that is the problem here though. ;-)