Use eval to dynamically save matrices

2 Ansichten (letzte 30 Tage)
fadams18
fadams18 am 15 Sep. 2022
Kommentiert: dpb am 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 Kommentare
John D'Errico
John D'Errico am 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 am 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...

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by