필터 지우기
필터 지우기

Structures with multiple, conntected anonymous functions

조회 수: 6 (최근 30일)
Kyle Johnson
Kyle Johnson 2020년 5월 13일
댓글: Kyle Johnson 2020년 5월 13일
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
Ameer Hamza
Ameer Hamza 2020년 5월 13일
What is f(b) in this line
y*f(b)+b*x
is it supposed to be fx(b)?
Kyle Johnson
Kyle Johnson 2020년 5월 13일
@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

댓글을 달려면 로그인하십시오.

채택된 답변

Ameer Hamza
Ameer Hamza 2020년 5월 13일
편집: Ameer Hamza 2020년 5월 13일
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
Kyle Johnson
Kyle Johnson 2020년 5월 13일
This is exactly what I have done. Thank you. I have marked this at the accepted answer for future readers.
Ameer Hamza
Ameer Hamza 2020년 5월 13일
I am glad to be of help.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by