Structures with multiple, conntected anonymous functions
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Kyle Johnson
am 13 Mai 2020
Kommentiert: Kyle Johnson
am 13 Mai 2020
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 Kommentare
Akzeptierte Antwort
Ameer Hamza
am 13 Mai 2020
Bearbeitet: Ameer Hamza
am 13 Mai 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 Kommentare
Weitere Antworten (1)
the cyclist
am 13 Mai 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 Kommentare
James Tursa
am 13 Mai 2020
Yes, it appears you understand how function handles work now. Your current approach seems correct to me.
Siehe auch
Kategorien
Mehr zu Whos finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!