How do I get a structure to include all the data that I want?

1 次查看(过去 30 天)
folder_list = dir([data_dir filesep currentfolder(3).name]);
this is my code. I want folder_list to grab everything from 3 to 7. if I use a simple for loop from 3:7, it just gives me the data for 7.
  5 个评论
Stephen23
Stephen23 2022-9-3
编辑:Stephen23 2022-9-3
Jan
Jan 2022-9-3
@Khush Patel: Do not do this:
addpath(genpath(pwd));
Adding the folder, which contains data files, to Matlab's PATH has no advantage, but severe disadvantages. Matlab's PATH should include only the folders containing the M-files of the used functions. Use absolute path names for data files instead:
fid = importdata(fullfile(data_dir, folder_list(ifolder).name));
I do not see in your code the command matching the description "if I use a simple for loop from 3:7".

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2022-9-2
For example, to read all png files in all subfolders of data_dir, storing the input as a cell array of cell arrays broken up by folder.
dinfo = dir(data_dir);
dinfo(~[dinfo.isdir]) = []; %remove non-folders
dinfo(ismember({dinfo.name}, {'.', '..'})) = []; %remove . and ..
foldernames = fullfile({dinfo.folder}, {dinfo.name});
numfolders = length(foldernames);
folder_images = cell(numfolders, 1);
for D = 1 : numfolders
thisfolder = foldernames{D};
finfo = dir(thisfolder, '*.png');
filenames = fullfile({finfo.folder}, {finfo.name});
numfiles = length(filenames);
these_images = cell(numfiles, 1);
for F = 1 : numfiles
thisfile = filenames{F};
these_images{F} = imread(thisfile);
end
folder_images = these_images;
end
  5 个评论
Image Analyst
Image Analyst 2022-9-3
Why 3-7? Are you trying to avoid . and .. which is what this does:
currentfolder(~[currentfolder.isdir]) = []; %remove non-folders
or are your first and second folder not . and ..?
Walter Roberson
Walter Roberson 2022-9-3
No, I cannot do that. Your current code is incorrect in design.
You should never rely on the relative position of files within a folder. None of the file systems you are likely to ever encounter impose any internal ordering on names, and none of the operating systems supported by MATLAB define a fixed order to return names in response to queries of directory information.
The NTFS file system commonly used by Windows has some "typical" behaviour, but the typical behaviour is not strictly adhered to, and is different from what most people expect... and depends in part on the region setting of the user who created the file system. So copying between drives can result in different ordering of files.
You should always code in terms of accepting or rejecting files based upon names or other attributes, not on the basis of order of files returned by dir()

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by