How to save mat file using save() with a different variable name using for loop

조회 수: 13 (최근 30일)
a=[1,2,3,4,5,6,7,8,9];
b=[m,n,o,p,q,r,s,t,u];
for i=1:9
save('2_back_gp_1_trial_ str2num(a(i))_sub_1.mat',' b(i)')
end

답변 (1개)

Stephen23
Stephen23 2022년 3월 6일
편집: Stephen23 2022년 3월 6일
"How to save mat file using save() with a different variable name using for loop"
That rather poor data design that seems to be tempting the use of dynamic variable names:
It could be done by dynamically naming a structure field and then using the -struct option, e.g.:
V = 1:9;
C = 'm':'u';
for k = 1:numel(V)
b = V(k);
S = struct(C(k),b);
F = fprintf('file_%d.mat',b);
save(F,'-struct','S')
end
However your code would be simpler and more efficient if you simply used exactly the same variable name in every file, e.g.:
V = 1:9;
for k = 1:numel(V)
b = V(k);
F = fprintf('file_%d.mat',b);
save(F,'b')
end

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by