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

12 views (last 30 days)
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

Answers (1)

Stephen23
Stephen23 on 6 Mar 2022
Edited: Stephen23 on 6 Mar 2022
"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

Categories

Find more on Loops and Conditional Statements 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!