What am I missing while using cellfun & eval together

5 次查看(过去 30 天)
sc = statechart1;
Prop = {'Config','DBIT'}
y = table('Size', [l 2], 'VariableTypes',{'double','logical'},'VariableNames', Prop);
for i=1:l
step(sc);
cellfun(@(x) eval("y." + x + "(i) = sc." + x + ";"),Prop);
end
The preceeding code produces the following error:
Unable to resolve the name sc.ConfigDuration
Now it is possible to fix by replacing the cellfun with:
for k=1:length(Prop)
eval("y." + Prop{k} + "(i) = sc." + Prop{k} + ";");
end
But for my own learning it would be nice to know what I'm missing with the cellfun implementation.

采纳的回答

Steven Lord
Steven Lord 2020-1-8
There's no need to use eval here. Instead, I would use table array indexing on y. I believe dynamic property indexing will work on statechart1, which I assume is a standalone chart, but I'm not 100% certain. Something along the lines of this should work, though I haven't tested it. I changed the variable names i (to whichstep) and lower-case L (to numberOfSteps) you used in your code for readability and to make them more clearly indicate their purposes.
sc = statechart1;
Prop = {'Config','DBIT'}
y = table('Size', [numberOfSteps 2], 'VariableTypes',{'double','logical'},'VariableNames', Prop);
for whichstep = 1:numberOfSteps
step(sc);
for whichprop = Prop
name = whichprop{1};
y{whichstep, name} = sc.(name);
end
end
  1 个评论
Daniel
Daniel 2020-1-9
Thanks Steven,
Although your code didn't work directly, not that you promised. Dynamic field referencing seems to have passed me by, allowing me to remove most of the eval() calls in my code saving a lot of runtime.
So the above chuck of the code I was able to reduce to
sc = statechart1;
Prop = {'Config','DBIT'};
y = table('Size', [numberOfSteps 2], 'VariableTypes', {'double','logical'},'VariableNames', Prop);
for whichstep = 1:numberOfSteps
step(sc);
y(whichstep, Prop) = cellfun(@(x), Prop,'UniformOutput',false);
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by