0

I have several .txt files of 2 columns, that I’d like to import and use the second column for subsequent operations. My text files are name as: profileA1.txt, profileA2.txt, etc… and my variables corresponding to the data of the second column are named in the subsequent code are A1, A2, A3, etc…

The code works but currently I have to open manually each .txt file with the Import data wizard, change the name of the second column and click on the import the selection. I tried to write a code (see below) to automatize these steps but it doesn’t work? Anyone has any idea to fix this code?

Thanks

for k = 1:5
     myfilename = sprintf('profileA%d.txt', k);
     mydata = importdata(myfilename);
     Aloop = ['A' num2str(k)];
     A{k} = load(myfilename.data(:,2), k);
end
sco1
  • 12,154
  • 5
  • 26
  • 48
JohnDeuf
  • 1
  • 1
  • Possible duplicate of [Read multiple text files and import each of them as columns](http://stackoverflow.com/questions/3459592/how-to-read-multiple-files-into-a-single-cell-array) – GameOfThrows Jul 05 '16 at 15:31
  • What is the format of your data files? Can you please explain your logic behind the provided code block? None of it makes any sense. Why are you using both `importdata` and `load`? What is the purpose of `Aloop`? Why are you trying to access the `data` field of `myfilename` when you have created `myfilename` as a string? Where did the `load` syntax come from? I highly recommend reading [MATLAB's documentation](http://www.mathworks.com/help/matlab/), it's very thorough. – sco1 Jul 05 '16 at 15:54
  • Alright after a bit of searching, I manage to do what I want with this command line : 'A15 = dlmread('profileA15.txt', '\s',1,1)'. But now, how can I make a loop for example between 15 and 19. – JohnDeuf Jul 07 '16 at 14:35

1 Answers1

0

You're example is a little off because you convert myfilename from a character array to a structure magically. I would approach this by reading the entire text file into a cell array of characters then using cellfun and textscan to read in the columns. Like this:

function C = ReadTextFile(infile)
if (exist(infile, 'file') ~= 2)
    error('ReadTextFile:INFILE','Unknown file: %s.\n', infile);
end

fid = fopen(infile, 'r');
C = textscan(fid, '%s', 'delimiter','\n');
C = C{1};
fclose(fid);

end

% assign an output file
outFile = 'SomeRandomFile.mat';

for k = 1:5
    C = ReadTextFile(sprintf(‘profileA%d.txt’, k));
    val = cell2mat(cellfun(@(x) textscan(x, '%*f %f','CollectOutput',1),C));
    varName = sprintf('A%d', k);        
    assignin('base', varName, val);
    save(outFile, varName, '-append')
end

You can skip the whole reading as a character array first but I have that function already so I just reused it.

Matt
  • 2,554
  • 2
  • 24
  • 45