save two variables using num2str

I want to save two variables using num2str, but I get error. what is wrong with this?
x1=1;
y1=2;
ty_c=1;
pathdatasave = (['D:\testa\ty' num2str(ty_c) '\']);
save([pathdatasave 'test_x' num2str(x1) '_y' num2str(y1) '.mat'],['varx' num2str(x1) ,'vary' num2str(y1)]);

댓글 수: 4

Stephen23
Stephen23 2022년 7월 11일
편집: Stephen23 2022년 7월 12일
"what is wrong with this?"
Forcing meta-data (e.g. pseudo-indices) into variable names is a sign of poor data design, which when you try to access your data forces you into writing slow, complex, inefficient, obfuscated, insecure, buggy code which is hard to debug (your code).
Ham Man
Ham Man 2022년 7월 11일
편집: Ham Man 2022년 7월 12일
I separated varx vary by individual brackets and it works fine:
save([pathdatasave 'test_x' num2str(x1) '_y' num2str(y1) '.mat'],['varx' num2str(x1)] ,['vary' num2str(y1)]);
Ham Man
Ham Man 2022년 7월 11일
Thanks for the time

댓글을 달려면 로그인하십시오.

답변 (1개)

Stephen23
Stephen23 2022년 7월 11일
편집: Stephen23 2022년 7월 12일

0 개 추천

"what is wrong with this?"
  1. Forcing meta-data (pseudo-indices) into variable names, thus making your code slow and complex.
  2. Forcing code into one line, when clarity is actually more important (as this question demonstrates).
  3. Two variable names must be supplied as two inputs to SAVE (not concatenated together as you are doing):
x1=1;
y1=2;
varx1 = 33;
vary2 = 444;
P = '.';
F = fullfile(P,sprintf('test_x%d_y%d.mat',x1,y1));
N1 = sprintf('varx%d',x1);
N2 = sprintf('vary%d',y1);
save(F,N1,N2);
% ^^ ^^ two variable names == two inputs, not one like you did!
Checking:
whos -file test_x1_y2.mat
Name Size Bytes Class Attributes varx1 1x1 8 double vary2 1x1 8 double
So, everything works exactly as documented and expected.

카테고리

도움말 센터File Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기

태그

질문:

2022년 7월 11일

댓글:

2022년 7월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by