0

How do I save a '.txt' file as a '.mat' file, using either MATLAB or Python? I tried using textscan() (in MATLAB), and scipy.io.savemat() (in Python). Both didn't help.

My text file is of the format: value1,value2,value3,valu4 (each row) and has over 1000 rows.

Appreciate any help is appreciated. Thanks in advance.

Dr. Strange
  • 87
  • 11

3 Answers3

3

You can use textscan to read the file and save to save the variables into a .mat file

fid = fopen('yourTextFile.txt');
C = textscan(fid,'%f %f %f %f');
fclose(fid);
% maybe change the cells from `C` to a single matrix
M = cell2mat(C);
save('myMatFile.mat','M');

This works because your file seems to have a fixed format. Have a look at this and this

user7431005
  • 3,899
  • 4
  • 22
  • 49
  • When I run this, I get the following error:Error using cat Dimensions of matrices being concatenated are not consistent. Error in cell2mat (line 75) m{n} = cat(2,c{n,:}); – Dr. Strange Nov 08 '18 at 17:17
  • Can you please give more information about the content of your file and the dimension of each cell in `C`. – user7431005 Nov 08 '18 at 21:07
1

I was able to get it to work using csvread() as follows:

file = csvread('yourTextFile.txt');
save('myMatFile.mat','file');
Dr. Strange
  • 87
  • 11
-3

if what you need is to change file format: mv example.mat example.txt

liaofeng
  • 82
  • 6