问题
I have 100 ASCII files in my directory all named as follows:
int_001.ASC
int_002.ASC
int_003.ASC
.
.
.
int_099.ASC
int_100.ASC
I have to import them in MATLAB all with importdata, which should work as follows:
A = importdata(\'int_001.ASC\', \' \', 9)
x = A.data(:,1)
y = A.data(:,2)
My question is: how can I avoid writing 100 times importdata
? Is there a way to write the first string only and then have all data uploaded?
Thanks
回答1:
fls = dir( 'int_*.ASC' );
for fi=1:numel(fls)
A{fi} = importdata( fls(fi).name, ' ', 9 );
% ...
end
UPDATE:
You may use string formatting to read the files according to their numbers:
for fi=1:100
A{fi} = importdata( sprintf('int_%03d.ASC', fi ), ' ', 9 );
% ...
end
回答2:
You can use strcat
function in a for loop :
for k=1:n
fileName = strcat('int_',num2str(k, '%03d'),'.ASC');
A(k) = importdata(fileName, ' ', 9);
x(k) = A(k).data(:,1);
y(k) = A(k).data(:,2);
end
回答3:
If you want to take this a little overboard:
alldata = arrayfun(...
@(dirEntry)importdata(dirEntry.name, ' ', 9), ...
dir('int_*.ASC'),...
'uniformoutput',false);
This line does the following
- Gets a listing of all files matching the partial filename, as an array of structures (h/t Shai)
- For each element in that array, performs the
importdata
call from your original post. - Compiles all the outputs into a cell array.
来源:https://stackoverflow.com/questions/15366374/how-can-i-load-100-files-with-similar-names-and-or-string-in-just-one-step-in-ma