Skip to content

Instantly share code, notes, and snippets.

@eug
Last active April 4, 2022 12:42
Show Gist options
  • Save eug/a3dce98d4c88b0934970ee7de8bb1ec5 to your computer and use it in GitHub Desktop.
Save eug/a3dce98d4c88b0934970ee7de8bb1ec5 to your computer and use it in GitHub Desktop.
Convert .mat to .csv file
import numpy as np
import pandas as pd
from scipy.io import loadmat
def mat2csv(file_mat, index=False):
mat = loadmat(file_mat, squeeze_me=True)
for colname in mat.keys():
# ignore private column names
if colname.startswith("__"):
continue
for fieldname in mat[colname].dtype.names:
# ignore struct fields different from "data"
# rename or uncomment it to match your needs
if fieldname != "data":
continue
# get dataset values from "data" field for current column
element = mat[colname][fieldname].item()
# it could exist other instances (eg. str) and other dimensions (eg. 1D)
# update these lines if you need something different than this
if isinstance(element, np.ndarray):
if len(element.shape) == 2:
_, cols = element.shape
data = {f"x{i}" : element[:, i] for i in range(cols)}
pd.DataFrame(data).to_csv(f"{colname}.csv", index=False)
mat2csv("filename.mat")
@thomjj824
Copy link

can i use this code to convert my mat file to csv?

Probably, yes.

how can mat file located into code?

I just updated the gist. You must replace line 31 specifying your filename.

hi !
i used your code and changed line 31
no errors and was able to run the code
but it doesn't give me a csv file ?
can you add a path for csv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment