How do you elegantly load dynamic variables into a cell array?
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Jan
2022-3-3
编辑:Jan
2022-3-3
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)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Simulink Functions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!