0

I have to read a lot of text files in a folder which only have one matrix in them. So I found and tested that dlmread is good when I write a file's name. But I couldn't have MATLAB read them all.

How can I correct this small code and If there is better way, please write.

files = dir('C:\Users\ABC\Desktop\a\*.txt')
for k = 1:length(files)
    fname= files(k).name
    M = dlmread('fname')   % This part is wrong
    % REST OF CODE for each Matrix M
end

well fname really reads the name of file, 1.txt for example. If I write M = dlmread('1.txt') myself, it reads matrix to M, but if I write M = dlmread('fname') it does not.

How can I do this best?

Suever
  • 64,497
  • 14
  • 82
  • 101
xcvbnm
  • 69
  • 9
  • Possible duplicate: http://stackoverflow.com/questions/11621846/loop-through-files-in-a-folder-in-matlab -- I didn't really get what you want. – Matthias W. Mar 31 '16 at 20:01
  • well fname really reads the name of file, 1.txt for example. If I write M = dlmread('1.txt') , it reads matrix to M, but if I write M = dlmread('fname') it does not. What should i do and How can i correct it. Thanks – xcvbnm Mar 31 '16 at 20:03
  • @xcbnm: ah got you. Should have seen it directly in the code. :D – Matthias W. Mar 31 '16 at 20:05

1 Answers1

3

you need:

for k=1:numel(files)
    fname = fullfile('C:\Users\ABC\Desktop\a', files(k).name);
    M = dlmread(fname);
    % ...
end

Two things:

  1. fname is a variable, not a literal string
  2. since the files are not in the current directory, you have to specify the full path
Amro
  • 123,847
  • 25
  • 243
  • 454