Demetri Pananos
Demetri Pananos

Reputation: 7404

Turning a python ndarray into a matlab file

So I have an CSV file that I have read into a list. I have turned that list into an array, and have saved the array into a MATLAB file with the following function.

def save_array(arr,filename):
    import scipy.io
    out_dict={}
    out_dict[filename]=arr
    scipy.io.savemat(filename + '.mat',out_dict)

However, when I open the MATLAB file, something goes wrong. When I open up in Python, I get the following output:

{'M': array([[u'153  ', u'81   ', u'0.28 ', ..., u'0.19 ', u'-0.07', u'1    '],
   [u'168  ', u'76   ', u'0.08 ', ..., u'0.98 ', u'0.42 ', u'0    '],
   [u'184  ', u'92   ', u'0.18 ', ..., u'0.92 ', u'0.75 ', u'0    '],
   ..., 
   [u'183  ', u'62   ', u'0.57 ', ..., u'0.87 ', u'0.31 ', u'0    '],
   [u'181  ', u'72   ', u'0.48 ', ..., u'0.91 ', u'1.2  ', u'0    '],
   [u'158  ', u'77   ', u'1.01 ', ..., u'0.99 ', u'0.88 ', u'0    ']], 
  dtype='<U5'),
 '__globals__': [],
 '__header__': 'MATLAB 5.0 MAT-file Platform: posix, Created on: Tue Nov  5 15:28:57 2013',
 '__version__': '1.0'}

Why is there a u at the beginning of each element? How can I rectify this?

Upvotes: 2

Views: 190

Answers (1)

Pablo Reyes
Pablo Reyes

Reputation: 3123

I see that you are reading the CSV file and getting an array of strings. You can convert them to an array of floating point numbers before saving them:

import numpy as np
out_dict[filename]=np.array(arr, dtype=np.float64)

Upvotes: 3

Related Questions