How to save a text file to a .mat file?

1.3k Views Asked by At

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.

3

There are 3 best solutions below

2
On

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

0
On

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

0
On

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

file = csvread('yourTextFile.txt');
save('myMatFile.mat','file');