0

How can read multiple files in from a directory using matlab? Can someone please help correct my code below:

files =dir(fullfile(directory_path,'*.dat'));
numfiles = length('*.dat');
mydat = cell(1, numfiles);

for k = 1:numfiles
    mydata{k} = fopen([directory_path,files(k).name]);
    values=textscan(mydata{k},'%s','delimiter','\n');
    fclose(fid);
    %fprintf(values)
    ....do something with values.....

end

.dat files are just many rows and single column of strings that need to be read in a loop and processed further.

Thanks

2 Answers 2

1

fopen gives file pointer, which you save to mydata{k}, and try to release by fclose(fid). There is no fid, so it doesn't work. What you should do is replace mydata{k} with fid. And probably values by mydata{k}.

The other bug is in numfiles = .... You will always have numfiles = 5, as there are 5 characters in the '*.dat'.

numfiles = length(files);

would be better, although you would also count directories. Check one of the other questions how to solve this.

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks Zizy Archer.

I solved the problem this way:

files =dir(fullfile(directory_path,'*.dat'));
numfiles = length(files);

for k = 1:numfiles
    textFileName = [directory_path,files(k).name]
    fid = fopen(textFileName, 'r');
    textData = textscan(fid,'%s','delimiter','\n');
    fclose(fid);

    data = textData{:,1}
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.