Effacer les filtres
Effacer les filtres

Structures with multiple, conntected anonymous functions

6 vues (au cours des 30 derniers jours)
Kyle Johnson
Kyle Johnson le 13 Mai 2020
Commenté : Kyle Johnson le 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 commentaires
Ameer Hamza
Ameer Hamza le 13 Mai 2020
What is f(b) in this line
y*f(b)+b*x
is it supposed to be fx(b)?
Kyle Johnson
Kyle Johnson le 13 Mai 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

Connectez-vous pour commenter.

Réponse acceptée

Ameer Hamza
Ameer Hamza le 13 Mai 2020
Modifié(e) : Ameer Hamza le 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 commentaires
Kyle Johnson
Kyle Johnson le 13 Mai 2020
This is exactly what I have done. Thank you. I have marked this at the accepted answer for future readers.
Ameer Hamza
Ameer Hamza le 13 Mai 2020
I am glad to be of help.

Connectez-vous pour commenter.

Plus de réponses (1)

the cyclist
the cyclist le 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 commentaires
James Tursa
James Tursa le 13 Mai 2020
Yes, it appears you understand how function handles work now. Your current approach seems correct to me.
Kyle Johnson
Kyle Johnson le 13 Mai 2020
Thanks for your help!

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by