What am I missing while using cellfun & eval together

2 visualizaciones (últimos 30 días)
Daniel
Daniel el 8 de En. de 2020
Comentada: Daniel el 9 de En. de 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.

Respuesta aceptada

Steven Lord
Steven Lord el 8 de En. de 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 comentario
Daniel
Daniel el 9 de En. de 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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Function Creation en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by