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

6 ビュー (過去 30 日間)
Sydney Lang
Sydney Lang 2022 年 3 月 3 日
コメント済み: Stephen23 2022 年 4 月 4 日
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.

採用された回答

Jan
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 件のコメント
Sydney Lang
Sydney Lang 2022 年 4 月 4 日
I had no idea you could index with ('') notation, thats so useful! Thank you, I'll defiently use the fast version.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSimulink Functions についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by