Same Functions but Return Different Values

6 views (last 30 days)
Ivy Zhong
Ivy Zhong on 28 Jan 2018
Edited: John D'Errico on 28 Jan 2018
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?

Answers (1)

John D'Errico
John D'Errico on 28 Jan 2018
Edited: John D'Errico on 28 Jan 2018
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. ;-)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!