How can I load 100 files with similar names and/or string in just one step in MATLAB?

為{幸葍}努か 提交于 2019-11-26 04:56:15

问题


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

  1. Gets a listing of all files matching the partial filename, as an array of structures (h/t Shai)
  2. For each element in that array, performs the importdata call from your original post.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!