How do you elegantly load dynamic variables into a cell array?
6 ビュー (過去 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)
2 件のコメント
その他の回答 (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!