Use eval to dynamically save matrices

2 ビュー (過去 30 日間)
fadams18
fadams18 2022 年 9 月 15 日
コメント済み: dpb 2022 年 9 月 15 日
Im trying to name my matrices in a loop according to a list of algorithms
I would like to have example GC_1 which contains some the matrix rRE
for c=["GC","VC"] % names of my algorithms
for i=1:2
for k=1:3
A(k,:)=rand(1,6);
end
A_hat = median(A); % matrix
temp_var = strcat( c,'_',num2str(i));
eval(sprintf('%s = %g',temp_var,A_hat));
end
end
% so I would like to have a variable GC_1 containing a matrix as its value.
it works when A_hat is an integer but doesnt work when A_hat is a matrix
% Error: Invalid expression. Check for missing multiplication operator, missing or unbalanced delimiters, or other syntax
% error. To construct matrices, use brackets instead of parentheses.
  5 件のコメント
John D'Errico
John D'Errico 2022 年 9 月 15 日
Please don't number your variables. Instead, learn to use arrays, cell arrays if needed. This will save your next anxious question, which will be: "How can I use my numbered variables, since I have hundreds of them?"
Using arrays properly is the way to write better code. Learn this style of programming, instead of using eval, which will cause you bugs, slow code, and many heartaches.
dpb
dpb 2022 年 9 月 15 日
"Please don't number your variables..."
Indeed. From medieval map charting terra incognito, the warning “Hic Svnt Dracones” is apropos here, too...

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

回答 (0 件)

カテゴリ

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