For Loop using xlsread indexing
2 次查看(过去 30 天)
显示 更早的评论
The following loop is giving me a warning of "The variable 'raw' appears to change size on every loop iteration (within a script). Consider preallocating for speed."
for Str = {'Red' 'Green' 'Orange' 'Purple' 'Pink'};
folder = '';
FileNames=dir('.xls');
for i = length(FileNames)
FileToLoad = FileNames(i).name;
[~,~,raw{i}] = xlsread(FileToLoad);
if exist(FileToLoad , 'file')==0
continue;
end
end
return;
end
Also, when the files are read into the 'raw' container they are not in the same order as they are listed in the Str. I want the files to be listed in raw table in the order that they are listed in the Str. Is this possible, as I use those indexes later on in my code.
Any suggestions are appreciated. Thanks
3 个评论
dpb
2020-7-2
编辑:dpb
2020-7-2
Well, it will stop when it's run a maximum of length(FileNamess) times; it's a counted loop. Of course, that could be a sizable number depending on what FileNames contains.
length is risky depending -- altho if one presumes based on use of the .Name field FileNames is the result of a dir() call (did you use wildcard to eliminate the "., .." directory entries?) it is a 1D struct array so you get what you expect. Read the documentation for length to see why it's not good in general.
The exist test is pretty-much pointless; dir() won't return an entry for a non-existing file so if you use something like
d=dir(fullfile('directoryString'),'*.xlsx');
for i=1:numel(d)
..
end
you'll only have the files with .xlsx extension; refine the wildcard expression to be more selective.
As far as the raw, save a variable, but the raw data will be a cell array of the size of the elements in the worksheet; it would probably be better to process each in turn before going on to the next--otherwise, you'll have to do something like create a 3D cell array or a cell array of cell arrays.
You also should probably look at and seriously consider readtable and returning the data as MATLAB table instead of the raw cell data.
采纳的回答
Walter Roberson
2020-7-2
编辑:Walter Roberson
2020-7-2
basenames = {'Red' 'Green' 'Orange' 'Purple' 'Pink'};
nbase = length(basenames);
raw = cell(nbase, 1);
for K = 1 : nbase
FileToLoad = [basenames{K} '.xls'];
if exist(FileToLoad, 'file')
[~,~,raw{K}] = xlsread(FileToLoad);
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!