1

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

Shai
  • 111,146
  • 38
  • 238
  • 371
ragnar
  • 57
  • 1
  • 4
  • 10

3 Answers3

11
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
Community
  • 1
  • 1
Shai
  • 111,146
  • 38
  • 238
  • 371
4

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
CTZStef
  • 1,675
  • 2
  • 18
  • 47
  • Maybe I've come to the point. By using fls = dir('int_*.ASC') now we have fls(1) = int_091.ASC. I typed fls(1) and what appears is: name = 'int_091.ASC', date = ... and so on. The problem is that if I do importdata('int_091.ASC', ' ', 9) everything is all right; instead, if I do importdata(fls(1), ' ', 9), MATLAB cannot work it out. Should I use a different command? – ragnar Mar 13 '13 at 11:24
2

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.
Pursuit
  • 12,285
  • 1
  • 25
  • 41