Filter löschen
Filter löschen

What am I missing while using cellfun & eval together

7 Ansichten (letzte 30 Tage)
Daniel
Daniel am 8 Jan. 2020
Kommentiert: Daniel am 9 Jan. 2020
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.

Akzeptierte Antwort

Steven Lord
Steven Lord am 8 Jan. 2020
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 Kommentar
Daniel
Daniel am 9 Jan. 2020
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by