hamed majidian
hamed majidian

Reputation: 1

How to store every element of a cell array in a separate folders?

I have a problem assigning and storing data to subfolders. I have one folder let's say a new folder, and I created 6 subfolders based on the size of a cell array. Now I want to save every element of the cell to subfolders in order but automatically. The following is my code and I was wondering how to make use of for loop to make it an automatic iteration. That is because it is going to be much more cell argument 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, how to assign n to simulation_Data (name of subfolders)?

Upvotes: 0

Views: 53

Answers (1)

magnesium
magnesium

Reputation: 455

You can change the number when reallocating folder the same way you do with filename - using sprintf:

for ii = 1:6 
    folder = spintf('C:\\Users\\HSH\\simulation_Data%d', ii); 
    filename = fullfile(folder, sprintf('image_%d.png' ii); 
    imwrite(adj_level2{1, ii}, filename); 
end

If you are doing this for numbers more than 9 or 99, you may want to consider using something like pad(int2str(ii), 4, 'left', '0') (see pad here) to help ensure that the folders are indexed in numerical/alphabetical order - but this is cosmetic only.

Upvotes: 1

Related Questions