For Loop using xlsread indexing
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
James
el 2 de Jul. de 2020
Comentada: Walter Roberson
el 2 de Jul. de 2020
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 comentarios
dpb
el 2 de Jul. de 2020
Editada: dpb
el 2 de Jul. de 2020
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.
Respuesta aceptada
Walter Roberson
el 2 de Jul. de 2020
Editada: Walter Roberson
el 2 de Jul. de 2020
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
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre File Operations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!