h_h10a
h_h10a

Reputation: 459

Converting multiple .txt files to .mat in the same folder

I have many .txt files that contain n rows and 7 columns each delimited with whitespace. I want to convert each file to .mat file and save that in the same folder.

I tried this but it's not working:

files = dir('*.txt');
for file = files'
    data=importdata(file.name);
    save(file.name, 'data');
end

While this works for a single file, i want to do it programmably since the number of .txt files i have is very large:

data=importdata('myfile.txt');
save('myfile', 'data');

Thank you for your help

Upvotes: 1

Views: 1740

Answers (2)

h_h10a
h_h10a

Reputation: 459

@scotty3785's answers worked well and also this worked for me in case somebody needs it:

files = dir('*.txt');
for i=1:length(files)
    data=importdata(files(i).name);
    save(erase(files(i).name,".txt"), 'data');
end

Upvotes: 2

scotty3785
scotty3785

Reputation: 7006

This should work

files = dir('*.txt');
for idx = 1:length(files)
   file_name = files(idx).name;
   fprintf("Processing File %s\n",file_name);
   data=importdata(file_name);
   [filepath,name,ext] = fileparts(fullfile(pwd,file_name));
   save([name '.mat'],'data');
end

dir creates a stucture which you need to index through so we create the for loop to start at 1 and keep going until all the elements of dir have been processed. Note in the code, I've also added a section to split the file name (e.g file1.txt) in to the file name and extension. This is so we only use the name part and not the extension when creating the mat file.

Upvotes: 2

Related Questions