How do I import file names that change in a loop?

1 次查看(过去 30 天)
I need to import Trial01, Trial02 and so on then Trial10, Triall11 but how do I define the 0 in the first 9 trails from 1 to 9 then not from 10 to 54?
This is my code to import the data:
%% Import data
numfiles = 54; % number of excel files mydata=cell(numfiles,1); % defining size of mydata d=dir('Trial*.csv');
for i=7:length(mydata) % loop to import mutliple excel files
try
mydata{i} = xlsread(d(i).name); % import files into mydata
catch
disp([d(i).name 'read failed'])
end
myfilename = sprintf('Trial%i.csv', i); % define file name
mydata{i} = xlsread(myfilename); % import files into mydata
  1 个评论
dpb
dpb 2014-5-12
编辑:dpb 2014-5-13
Again, I suggest just modify your present use of dir slightly instead.
It's well to know the format string to generate the place-holding 0 in a numeric field, and there are times when it's about the only choice but here there's still a very convenient wildcard pattern that works and it's still more work to generate names for existing files and you then have the problem of there may not be every one extant and you're back to a similar problem as that you have in the other thread of skipping empty content.
It does sometimes take a little creativity to get the right wild card--in this case,
d=[dir('Trial0?.csv');dir('Trial1?.csv')];
will return the values you want by concatenating the two directory structures for those from 00 thru 09 and 10-19, respectively. You can also get more exotic using post processing to eliminate those you don't want from a full dir() as an example is given in the doc's.

请先登录,再进行评论。

采纳的回答

per isakson
per isakson 2014-5-12
Change
'Trial%i.csv'
to
'Trial%02d.csv'

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by