现在我在 MATLAB 面前,这是一个基于我上面的评论的示例,利用动态字段名称 http://www.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html使用修剪的文件名fileparts http://www.mathworks.com/help/matlab/ref/fileparts.html and regexprep http://www.mathworks.com/help/matlab/ref/regexprep.html in a cellfun http://www.mathworks.com/help/matlab/ref/cellfun.html call.
% Sample list for testing here, use uigetdir with dir or whatever method to
% get a list of files generically
filelist = {'C:\mydata\2011-01-01.txt', ...
'C:\mydata\2012-02-02.txt', ...
'C:\mydata\2013-03-03.txt', ...
'C:\mydata\2014-04-04.txt', ...
};
nfiles = length(filelist);
% Get filenames from your list of files
[~, filenames] = cellfun(@fileparts, filelist, 'UniformOutput', false);
% Prune unwanted characters from each filename and concatenate with 'machine'
prunedfilenames = regexprep(filenames, '-', '');
myfieldnames = strcat('machine', prunedfilenames);
% Generate your structure
for ii = 1:nfiles
% Parse your files for the data, using dummy variables since I don't
% know how your data is structured
loadedsize = [1, 2, 3];
loadedweight = 1234;
loadedprice = 1234;
% Add data to struct array
mydata.(myfieldnames{ii}).size = loadedsize;
mydata.(myfieldnames{ii}).weight = loadedweight;
mydata.(myfieldnames{ii}).price = loadedprice;
end
@patrik 在评论中提出了一些好的观点。我认为他希望看到的更通用的方法(如果我错了,请纠正我)是这样的:
% Sample list for testing here, use uigetdir with dir or whatever method to
% get a list of files generically
filelist = {'C:\mydata\2011-01-01.txt', ...
'C:\mydata\2012-02-02.txt', ...
'C:\mydata\2013-03-03.txt', ...
'C:\mydata\2014-04-04.txt', ...
};
nfiles = length(filelist);
% Get filenames from your list of files
[~, filenames] = cellfun(@fileparts, filelist, 'UniformOutput', false);
% Prune unwanted characters from each filename and concatenate with 'machine'
prunedfilenames = regexprep(filenames, '-', '');
mytags = strcat('machine', prunedfilenames);
% Preallocate your structure
mydata = repmat(struct('tag', '', 'size', [1, 1, 1], 'weight', 1, 'price', 1), nfiles, 1);
% Fill your structure
for ii = 1:nfiles
% Parse your files for the data, using dummy variables since I don't
% know how your data is structured
loadedsize = [1, 2, 3];
loadedweight = 1234;
loadedprice = 1234;
% Add data to struct array
mydata(ii).tag = mytags{ii};
mydata(ii).size = loadedsize;
mydata(ii).weight = loadedweight;
mydata(ii).price = loadedprice;
end