Effacer les filtres
Effacer les filtres

What am I missing while using cellfun & eval together

5 vues (au cours des 30 derniers jours)
Daniel
Daniel le 8 Jan 2020
Commenté : Daniel le 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.

Réponse acceptée

Steven Lord
Steven Lord le 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 commentaire
Daniel
Daniel le 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

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by