How do you elegantly load dynamic variables into a cell array?

6 views (last 30 days)
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))
ans = 1×3
1 1 1
nodes = 1:3;
% loop - WORKS
for k = nodes
A{k} = eval(sprintf("out.A%0.0f.Data",k));
end
A
A = 1×3 cell array
{[1 1 1]} {[2 2 2]} {[3 3 3]}
% arrayfun - FAILS
arrayfun(@(x) eval(sprintf("out.A%0.0f.Data",x)),nodes,"UniformOutput",false)
Unable to resolve the name out.A1.Data.

Error in solution (line 13)
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.

Accepted Answer

Jan
Jan on 3 Mar 2022
Edited: Jan on 3 Mar 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)

More Answers (0)

Categories

Find more on Simulink Functions in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!