フィルターのクリア

Using string saved variables for calculations

1 回表示 (過去 30 日間)
Guillermo Lopez
Guillermo Lopez 2012 年 6 月 4 日
If I have variables with varying names (Z_1,Z_2,Z_3,etc) with assigned values of z made by num2str as shown below;
for v=1:18
eval(['Z_' num2str(v) '=z'])
end
and each has stored a matrix inside (Z_1 is a 10x10 matrix, and so on for each Z_n), and I want to sum up the matrices without having to enter TotalZ=Z_1+Z_2+Z_3...Z_18, is there any quick way of referring to the variables? I mean, something of the kind of :
TotalZ=sum('Z_'num2str(v))
I can't seem to find a way of using those stored variables to o anything, if I dont enter them directly by hand. I need to know the right way of referring to the variables for using them for any calculation. Thanks in advance.

採用された回答

Titus Edelhofer
Titus Edelhofer 2012 年 6 月 4 日
Hi,
generally speaking you can do the same as before:
TotalZ = 0;
for v=1:18
TotalZ = TotalZ + eval(['Z_' num2str(v)]);
end
But I would suggest to use cellarrays directly:
allZ = cell(1, 18);
for v=1:18
all{v} = z;
end
Working with the cell array later will be much easier, e.g.,
allZ3D = cat(3, allZ{:});
TotalZ = sum(allZ3D, 3);
Titus
  1 件のコメント
Guillermo Lopez
Guillermo Lopez 2012 年 6 月 4 日
Thank you very much. Works well

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2012 年 6 月 4 日

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by