Use eval to dynamically save matrices

1 vue (au cours des 30 derniers jours)
fadams18
fadams18 le 15 Sep 2022
Commenté : dpb le 15 Sep 2022
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 commentaires
John D'Errico
John D'Errico le 15 Sep 2022
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 le 15 Sep 2022
"Please don't number your variables..."
Indeed. From medieval map charting terra incognito, the warning “Hic Svnt Dracones” is apropos here, too...

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by