Problems converting folders in a directory from cell array into individual nested structures.
Show older comments
I have written a code to first read all folders in a directory and convert them into separated nested structures but the code I found in Community page only gives a cell array. Diagram 3 is the end result I am trying to get. Within each folder (e.g TE_View_02_24mm_10deg_f11_1.1deg) contains the structure 'KeyData'.
TopLevelFolder = "C:\Users";
files = dir(TopLevelFolder); % Get a list of all files and folders in this folder.
dirFlags = [files.isdir]; % Get a logical vector that tells which is a directory.
subFolders = files(dirFlags); % A structure with extra info.
% Get only the folder names into a cell array.
subFolderNames = {subFolders(3:end).name}; % Start at 3 to skip . and ..
Items = {'Folder_Names'};
Folders = cell2struct(subFolderNames, Items, 1);
SampleData1 = zeros(256,512);
SampleData2 = zeros(1,512);
KeyData = struct('x',SampleData1,'y',SampleData1,'U',SampleData1, 'V', SampleData1,'Vorticity',SampleData2,'Circulation',SampleData2);
for i = 1:length(subFolderNames)
Given_Folders(i).Names = struct(Folders(i).Folder_Names,KeyData);
end

Diagram 1: Folders' name

Diagram 2: Error statement

Diagram 3: Desired outcome
1 Comment
Your code is very convoluted. Instead of simply using DIR's output (which would give you the folder names without any extra effort), you use indexing to create another structure array which you convert to a cell array using a comma-separated list which you then convert back to a structure array with only one field which you then refer to when creating a scalar structure which you then nest inside another new structure array.
This is waaaaaay too complex for such a simple task. So many structure arrays, all containing the same information: rather than duplicating the file information in lots of variables (i.e. FILES, SUBFOLDERS, FOLDERS, GIVENFOLDERS) why not just use the same structure? The code is a very convoluted way to simply keep the same information.
Note that this is a buggy attemp to remove the dot directory names:
subFolderNames = {subFolders(3:end).name}; % !!! BUGGY !!!
The robust approach is to use ISMEMBER, SETDIFF, or similar. For more information, see:
As Walter Roberson wrote in that last link: "In short: if your code assumes that '.' and '..' are the first two entries in a directory, your code has a bug (even in MS Windows). If your code assumes that directory entries are returned in any sorted order, your code has a bug (in all OS.)"
Accepted Answer
More Answers (0)
Categories
Find more on Structures 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!
