how to store every element of a cell array in a separate folders

4 views (last 30 days)
Hello everyone,
I'm kind of newto matlab, and I have a problem in assigning and storing data to subfolders. I have one folder let say newfolder, and I created 6 subfolders based on the sizee of cell array. Now I want to save every elemnt of cell to subfolders in order but automatically. in the following is my code and I was wondering how to make use of for loop to make it automatic iteration. That is because it is going to be much more cell argumanet later for example 50 to 100.
here is the code
n = 1;
folder = 'C:\Users\HSH\Desktop\MATLABCOURSE\simulation_Data1';
fileName = fullfile(folder, sprintf('image_%d.png', n));
imwrite( adj_level2{1,n}, fileName);
folder = 'C:\Users\HSH\Desktop\MATLABCOURSE\simulation_Data2';
n1=n+1;
fileName = fullfile(folder, sprintf('image_%d.png', n1));
imwrite( adj_level2{1,n1}, fileName);
folder = 'C:\Users\HSH\Desktop\MATLABCOURSE\simulation_Data3';
n2=n1+1;
fileName = fullfile(folder, sprintf('image_%d.png', n2));
imwrite( adj_level2{1,n2}, fileName);
folder = 'C:\Users\HSH\Desktop\MATLABCOURSE\simulation_Data4';
n3=n2+1;
fileName = fullfile(folder, sprintf('image_%d.png', n3));
imwrite( adj_level2{1,n3}, fileName);
folder = 'C:\Users\HSH\Desktop\MATLABCOURSE\simulation_Data5';
n4=n3+1;
fileName = fullfile(folder, sprintf('image_%d.png', n4));
imwrite( adj_level2{1,n4}, fileName);
folder = 'C:\Users\HSH\Desktop\MATLABCOURSE\simulation_Data6';
n5=n4+1;
fileName = fullfile(folder, sprintf('image_%d.png', n5));
imwrite( adj_level2{1,n5}, fileName);
more accurately I dont know how to assign n to simulation_Data (name of subfolders). Any help would be deeply appreciated. Regards

Answers (1)

Stephen23
Stephen23 on 1 May 2022
As soon as you start numbering variable names like n1, n2, n3, ... then you have painted yourself into a corner and made your task more difficult.
This should get you started:
N = numel(adj_level2);
P = 'C:\Users\HSH\Desktop\MATLABCOURSE';
for k - 1:N
D = sprintf('simulation_Data%d',k);
F = sprintf('image_%d.png',k);
T = fullfile(P,D,F);
imwrite(adj_level2{1,k}, T);
end
  1 Comment
Hamed Majidiyan
Hamed Majidiyan on 1 May 2022
Dear Stephen,
Oh got it. such an idiot I was. Thanks a billion for your help. I got the principle now.
All the best

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!