Use eval to dynamically save matrices

1 view (last 30 days)
fadams18
fadams18 on 15 Sep 2022
Commented: dpb on 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 Comments
John D'Errico
John D'Errico on 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 on 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...

Sign in to comment.

Answers (0)

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!