Convert mat file to excel python

The function scipy.io.loadmat generates a dictionary looking something like this:

{'__globals__': [],
 '__header__': 'MATLAB 5.0 MAT-file, Platform: MACI, Created on: Wed Sep 24 16:11:51 2014',
 '__version__': '1.0',
 'a': array[[[1, 2, 3]], dtype=uint8],
 'b': array[[[4, 5, 6]], dtype=uint8]}

It sounds like what you want to do is make a .csv file with the keys "a", "b", etc. as the column names and their corresponding arrays as data associated with each column. If so, I would recommend using pandas to make a nicely formatted dataset that can be exported to a .csv file. First, you need to clean out the commentary members of your dictionary [all the keys beginning with "__"]. Then, you want to turn each item value in your dictionary into a pandas.Series object. The dictionary can then be turned into a pandas.DataFrame object, which can also be saved as a .csv file. Your code would look like this:

import scipy.io
import pandas as pd

mat = scipy.io.loadmat['matex.mat']
mat = {k:v for k, v in mat.items[] if k[0] != '_'}
data = pd.DataFrame[{k: pd.Series[v[0]] for k, v in mat.items[]}] # compatible for both python 2.x and python 3.x

data.to_csv["example.csv"]

Star

Embed

What would you like to do?

Converting mat files to csv using python, scipy and pandas

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

import scipy.io
import pandas as pd
mat = scipy.io.loadmat['file.mat']
mat = {k:v for k, v in mat.items[] if k[0] != '_'}
data = pd.DataFrame[{k: pd.Series[v[0]] for k, v in mat.iteritems[]}]
data.to_csv["example.csv"]

  • Direct link to this question

 ⋮ 

  • Direct link to this question

Please help me out in a detail manner xlswrite command is not working

  8 Comments

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

please show the code that you already tried?

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Hi I tried to convert my .mat data to .xls but unable to do it. The .mat file data struct contains huge amount of data i.e the 107968x1 for all the variables. I want to convert it to a .xls can anyone give idea in this regard.

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Xls files are limited to 65535 rows. If you managed to create a file that big then Excel itself would be unable to read it.

You will need to use xlsx

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Can i export my .mat file data to xlsx? Is there any procedure for doing with matlab code? Please advise...

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

xlswrite[] can write .xlsx files.

If your data is in the form of a table[] or timetable[] object, then writetable[] can write it to .xlsx

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

I have an error for converting .mat files into .xlsx files ,I used this code

load['train_subject01.mat']

xlswrite['kokytest.xlsx', train_subject01]

and matlab gives me this error message

Undefined function or variable 'train_subject01'.

so please could anyone help me to solve it ?

Thanks in advance

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Your .mat file train_subject01.mat did not contain a variable named train_subject01 . You should use

whos -file train_subject01.mat

to see the names of the variables in the file.

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

我做了一个matToExcel工具可以在线处理这个问题

Sign in to comment.

Accepted Answer

  • Direct link to this answer

 ⋮ 

  • Direct link to this answer

data=load['FileName'];

f=fieldnames[data];

for k=1:size[f,1]

xlswrite['FileName.xlsx',data.[f{k}],f{k}]

end

  15 Comments

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Thanks for your reply Actually the problem is in my mat file i have many date types like CELL, Structure,character etc.

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Doesn't matter. Just make up one big cell array with all your various variables in it, and pass it to xlswrite[].

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Should still work, Azzi's answer puts everything on it's own sheet.

If you know how you want your excel to look, format into a giant cell [per sheet], ala Image Analyst's answer.

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

thank you, i have a same problem and this work for me.

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

i also have the same problem and now it has been solved. thanks!

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Thank you the mat file successfully saved as excel sheet

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Thank you so much. It worked

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Hi,

I used the code provided by Azzi to write a .mat file to .xlsx, but halfway through Matlab provides a warning saying that it will use writecsv instead. To quicken the process, I tried changing the xlswrite to csvwrite [perhaps naively so] and Matlab keeps coming up with the error: 'not a valid attribute or row offset'. What would be the best way to use csvwrite with a pre saved .mat file?

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

I am getting the below error

Error using xlswrite [line 170]

Input data must be a numeric, cell, or a logical array

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

When you see a warning that writecsv will be used instead, then you know that either you are not using MS Windows, or else you are using MS Windows but Excel cannot be found. In such a case you should switch to using writetable[] instead if possible.

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

xlswrite[] cannot be used to write variables of arbitrary datatype to xls or xlsx files. It can only be used to write numeric arrays, or logical arrays, or cell arrays in which each entry is a numeric value, or a logical value, or a character vector [or, these days, a string[] scalar].

writetable[] can handle some additional datatypes, but some datatypes it will simply leave empty cells for. For example, it will leave empty cells for Control System Toolbox transfer functions, or for symbolic expressions.

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Hi,

I am trying to convert an output mat file which contains 1.5MM rows of numbers to an excel file.Smeone suggested I change it from 3D to 2D first. I tried the following codes and nothing works. Can you fix it?

S=load['QQ_full.mat'];

data=S.QQ;

data=reshape[data,size[data,1]*size[data,2],size[data,3]];

writetable[S.QQ,data,'Sheet',1,'Range','A1']

Error using writetable [line 248]

Unsupported type 'double'. Use writematrix instead.

Did you mean:

>> writematrix[S.QQ,data,'Sheet',1,'Range','A1']

Error using matlab.io.xml.internal.write.errorIfXML [line 6]

FILENAME must be a non-empty character vector or string scalar.

Error in writematrix [line 196]

fileType = matlab.io.xml.internal.write.errorIfXML[filename, supportedFileTypes, varargin{:}];

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

Okay, at that point S.QQ and data are the same.

data=reshape[data,size[data,1]*size[data,2],size[data,3]];

and data gets reshaped so S.QQ and data now have the same content but different shape.

writematrix[S.QQ,data,'Sheet',1,'Range','A1']

You are asking to write out S.QQ, which is the original shape, and you are asking that it be written to a file whos name is stored in data .

You should be using something like

writematrix[data, 'Q_reshaped.xlsx', 'Sheet', 1, 'Range', 'A1']

However...

I am trying to convert an output mat file which contains 1.5MM rows of numbers to an excel file.

You have a problem. The largest file that excel supports is 1048576 rows, and you are creating more rows when you reshape.

The maximum number of columns for excel is 16384, so you would need to use permute[] and reshape[] to re-arrange your data to have fewer rows but more columns, but still fit within the 2^20 x 2^14 = 2^34 element = 16 giga-element [powers-of-two meaning of "giga" here]. If numel[s.QQ] > 2^34 then you have no hope of fitting it into a single excel sheet.

You might want to write sections to different sheets.

What is size[S.QQ] ?

Sign in to comment.

More Answers [1]

  • Direct link to this answer

 ⋮ 

  • Direct link to this answer

how to load my own datset for training and testing....

nprtool only respond inbuilt or example dataset..not my dataset,,,,

  2 Comments

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

How are your datasets represented? nprtool permits you to indicate which variable to use, or if you use the '...' button to the right of that, you can select a text file or .mat file to read data from.

Direct link to this comment

 ⋮ 

  • Link

    Direct link to this comment

This code working fine[mat to xls].

Sign in to comment.

See Also

Categories

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.


How do I convert a mat file to Excel?

Type the command "load NewFile" in the command window and press the "Enter" key, where "NewFile" is the name of the ". mat" file you wish to convert to an ". xls" file. This command will load the contents of the ".

How do I read a .MAT file?

How to Open an MAT File. MAT files that are Microsoft Access Shortcut files can be created by dragging a table out of Access and to the desktop or into another folder. Microsoft Access needs to be installed in order to use them. MATLAB from MathWorks can open MAT files that are used by that program.

Can we read .MAT file in Python?

Matlab 7.3 and greater Beginning at release 7.3 of Matlab, mat files are actually saved using the HDF5 format by default [except if you use the -vX flag at save time, see in Matlab]. These files can be read in Python using, for instance, the PyTables or h5py package.

How do I run a .MAT file in Python?

How to read ..
Install scipy. Similar to how we use the CSV module to work with . ... .
Import the scipy. io. ... .
Parse the . mat file structure. ... .
Use Pandas dataframes to work with the data. Now that you have the information and the data retrieved, how would you work with it?.

Chủ Đề