How do you elegantly load dynamic variables into a cell array?
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sydney Lang
el 3 de Mzo. de 2022
Comentada: Stephen23
el 4 de Abr. de 2022
I have a chain on outputs coming out of Simulink. The order of the outputs matter, hence the numbering.
When working with it in MATLAB, I would much prefer to reference this data as A{1}, A{2}, ect, so I can expand my system seamlessly. I tried setting the To Workspace blocks to A{1}, A{2}, ect in Simulink but it didn't like that. So I've been attempting to use arrayfun + eval in MATLAB to feed these variables into a single cell array. Eval returns the value I expect but it won't feed it into arrayfun.
% dummy data for demo purposes
out.A1.Data = [1 1 1]; out.A2.Data = [2 2 2]; out.A3.Data = [3 3 3];
% eval - WORKS
eval(sprintf("out.A%0.0f.Data",1))
nodes = 1:3;
% loop - WORKS
for k = nodes
A{k} = eval(sprintf("out.A%0.0f.Data",k));
end
A
% arrayfun - FAILS
arrayfun(@(x) eval(sprintf("out.A%0.0f.Data",x)),nodes,"UniformOutput",false)
What am I missing? I know I can do this in a loop, but I feel like there is a sleeker solution. The whole point of arrayfun is to condense one line loops, which is exsactly what I'm calling.
0 comentarios
Respuesta aceptada
Jan
el 3 de Mzo. de 2022
Editada: Jan
el 3 de Mzo. de 2022
Avoid eval. Instead of
eval(sprintf("out.%s.Data","A1"))
this is faster, safer and nicer:
out.('A1').Data
Then the loop becomes:
for k = 1:3
A{k} = out.(sprintf('A%d', k)).Data;
end
If you want to do this without a loop (although this is slower):
out.A1.Data = [1 1 1]; out.A2.Data = [2 2 2]; out.A3.Data = [3 3 3];
A = cellfun(@(x) x.Data, struct2cell(out), 'UniformOutput', false)
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Simulink Functions en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!