Structures with multiple, conntected anonymous functions

8 views (last 30 days)
I have a rather complicated workflow, however, I am having trouble identifying a way for it to work.
I start with a json of the form:
{
"x":3,
"y":6,
"fx":"@(a) a^2+y",
"fy":"@(a,b) y*fy(b)+b*x"
}
This gets read in and evaluated such that:
S.x = 3
S.y = 6
S.fx = @(a) a^2+y
S.fy = @(a,b) y*f(b)+b*x
I have tried both eval and str2funct to create the anonymous function.
Later in the workflow, this structure gets packaged into another structure
dS.S = S;
This is to help with passing a model around between functions.
The problem is, that later on, this command will give an error:
dS.S.fy(1,1)
The error states that the function fx cannot be found. However,
dS.S.fx(1)
does work, WITHOUT there being an "y" defined in the workspace.
Can anyone shed some light on this?
  3 Comments
Ameer Hamza
Ameer Hamza on 13 May 2020
What is f(b) in this line
y*f(b)+b*x
is it supposed to be fx(b)?
Kyle Johnson
Kyle Johnson on 13 May 2020
@James Tursa, they do not need to pick up S.x or S.y. These values will not change once they are read in.
@Ameer Hamza, yes that is a typo

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 13 May 2020
Edited: Ameer Hamza on 13 May 2020
Ok. I know "eval is evil" but here it makes everything quite simple in this case. You can define a helper function like this
function s = helperFun(s)
names = fieldnames(s);
for i=1:numel(names)
eval(sprintf('%s=s.%s;', names{i}, names{i}));
end
for i=1:numel(names)
if ischar(s.(names{i}))
s.(names{i}) = eval(s.(names{i}));
end
end
end
and then call it on your json file like this
S = jsondecode(fileread('test.txt'));
S = helperFun(S)
ds.S = S;
Then call the functions
>> ds.S.fx(1)
ans =
7
>> ds.S.fy(1, 2)
ans =
246
  2 Comments
Kyle Johnson
Kyle Johnson on 13 May 2020
This is exactly what I have done. Thank you. I have marked this at the accepted answer for future readers.

Sign in to comment.

More Answers (1)

the cyclist
the cyclist on 13 May 2020
Are you sure that y didn't exist in the workspace when you defined the structures? Because in a fresh workspace,
S.x = 3
S.y = 6
S.fx = @(a) a^2+y
S.fy = @(a,b) y*f(b)+b*x
dS.S = S
dS.S.fx(1)
gives the error
Unrecognized function or variable 'y'.
Error in @(a)a^2+y
Does that shed light?
  9 Comments
James Tursa
James Tursa on 13 May 2020
Yes, it appears you understand how function handles work now. Your current approach seems correct to me.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!