What am I missing while using cellfun & eval together

4 ビュー (過去 30 日間)
Daniel
Daniel 2020 年 1 月 8 日
コメント済み: Daniel 2020 年 1 月 9 日
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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by