Convert .mat file to .csv file using csvwrite

I thought of practicing the Neural Network exercise from Andrew Ng course in R and got stuck at the first step. The data file is in .mat format and I wanted to convert it in a .csv file. After a few trials and getting lots of errors, I finally got a solution and this post is about that solution.

Problem:

Convert a .mat file to a .csv file

Solution:

So the first thing I tried is using csvwrite in Octave like below:

cd '/Users/oindrilasen/WORK_AREA/Data Science/Stanford/Assignments/machine-learning-ex4/ex4'
datafile = load('ex4data1.mat')
csvwrite(ex4data1.csv,datafile)

The above statement created a blank .csv file in the same folder with name as “ex4data1.csv” and I got the below error:
error: fprintf: wrong type argument ‘scalar struct’
Being Clueless, I thought of checking the class of “datafile” and what is in there.

Here goes the output of the above commands in Octave:


First, we load the ‘ex4data1.mat’ file in “datafile”. The above commands point out that “datafile” is of class “struct” and has 2 fields “X” and “y”. “X” is a 5000 * 400 matrix and “y” is 5000 * 1 matrix. Now, let’s try to write each field in separate files. 


Two different files got created in the same working directory.  Now, let’s load the files in R and take a look at the data.

So, we loaded the two .csv files in R separately and combine them together in the data frame “digits”. If we check the structure of “digits”, it has 5000 observations and 401 variables as expected.



Well, this is just a solution for me to start with. I am sure, there must be some other ways of importing Matlab files in R. I will keep my notes updated as soon as I learn something new. 

Edit1: Okay, I got another solution by using library R.matlab directly from R environment. We do not need to connect to the octave for this solution.

0

2 comments

Leave a Reply

Your email address will not be published. Required fields are marked *