-1

I have a folder of .mat files (thousands of files) with specific names such as

FD800-000-M300.mat
MD500-234-K400.mat

...

and I would like to convert them into csv files and save them with same name they had as .mat files as

FD800-000-M300.csv
MD500-234-K400.csv

...

Please let me know the best way to do it in MATLAB.

1 Answers1

1

Assuming you have arrays there:

files = dir('/path/to/files/*.mat');
for file = files'
    [filepath, name, ext] = fileparts(file.name);
    csvwrite([name '.csv'], dlmread(file.name)); % Use readmatrix instead of dlmread in latast versions
    % Do some stuff
end

Note if you need to specify a delimiter that can be a second argument fot dlmread. You can refer to the docs for more options.

kabanus
  • 24,623
  • 6
  • 41
  • 74
  • This code does not give me any output. I only changed ```files = dir('/myfile/*.mat');```, and used ```readmax```, but I feel that ```file=files'``` part should change too. –  Nov 12 '20 at 02:41
  • @Sarah If you're in the same library as your files, you just need `dir('*.mat')`. I don't know what `/myfile/` is supposed to mean in this context. Try and `disp(file)` in the loop. If it's not displaying anything then it did not enter the loop, so it found no files and you need to make sure you `dir` correctly. – kabanus Nov 12 '20 at 05:48
  • Are you sure about that `name + '.csv'`? `fileparts` returns char, not string, so you might need `[name '.csv']` instead. And I think you need `fileparts(file.name)` and `flmread(file.name)` instead of just `fileparts(file)`; `dir()` returns a struct array. – Andrew Janke Nov 12 '20 at 06:10
  • @AndrewJanke Good points, I didn't check (worked from my head). I'll have a look soon, thanks. – kabanus Nov 12 '20 at 06:22
  • Someday there'll be a Matlab X release with nothing but `string` arrays and most of this headache will all go away... ;) – Andrew Janke Nov 12 '20 at 06:29
  • @AndrewJanke I hope for my grandchildren. Or maybe the industry will move on from Matlab in a parallel dimension. In any case, you were right, thanks again! – kabanus Nov 12 '20 at 12:07
  • @Sarah note Andrew's fixes, I changed the code to incorporate them. – kabanus Nov 12 '20 at 12:07
  • Thank you so much for the comments and collaboration. After putting the files in the right directory, now I am getting the error ```Error using dlmread (line 147) Mismatch between file and format character vector. Trouble reading 'Numeric' field from file (row number 1, field number 1) ```, I am using MATLAB 2018a. –  Nov 12 '20 at 14:32
  • @Sarah looks like those are not arrays/matrices. Please include in the question what these are (even better, what command you have used to save them). – kabanus Nov 13 '20 at 08:07