dynamically save a matrix to a structure

22 ビュー (過去 30 日間)
A
A 2021 年 1 月 23 日
編集済み: Stephen23 2021 年 1 月 26 日
I have a loop that evaluates a matrix X for each scenario. The size of this matrix X changes at each iteration, and the values too. I would like to make a structure X.1, X.2 etc to X.(n), and save the result X. When I do eval(['[Z.SET'num2str(J) ']= (Xtmp);']); X.1 gets overwritten by X.2, what I mean is that at first I have X.1 with the desired X matrix, but at the next loop, X.1 is no longer there and there is X.2 (with the corresponding X matrix). How can I “save” the X.1 so that it doesn’t get overwritten?

採用された回答

Stephen23
Stephen23 2021 年 1 月 24 日
編集済み: Stephen23 2021 年 1 月 26 日
Do NOT use eval for trivial code like this.
That approach is slow, complex, inefficient, and not recommended. Rather than messing around with fieldnames like that, the simple and efficient MATLAB solution would be to just use indexing into a cell array or structure array, e.g.:
C = cell(1,N);
for k = 1:N
...
C{k} = Xtmp;
end
Or if you really want to use a structure:
C = struct('X',cell(1,N));
for k = 1:N
...
C(k).X = Xtmp;
end

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by