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 CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by