user3792245
user3792245

Reputation: 828

Python output readable in Matlab

I am a Python newbie and am trying to write a numpy array into format readable in Matlab in the following format into an array [xi, yi, ti], separated by a semi-colon.

In python, I am able to currently write it in the following form, which is a numpy array printed on screen/written to file as [[xi yi ti]].

Here is the code:

import math
import random
import numpy as np
SPOT = []
f = open('data_dump.txt', 'a')
for i in range(10):
    X = random.randrange(6)
    Y = random.randrange(10)
    T = random.randrange(5)
    SPOT.append([X,Y,T])
SPOT = np.array(SPOT)
f.write(str(SPOT[:]))   
f.close()

Please suggest how I should proceed to be able to write this data in Matlab readable format as mentioned above. Thanks in advance!

Sree.

Upvotes: 1

Views: 412

Answers (4)

user3792245
user3792245

Reputation: 828

Thanks everyone and thanks @CT Zhu for letting me know!

Since I am not using Scipy, I tried using np.savetxt and it seems to work! Added the following and it writes into a format that is readable in Matlab as an array directly. Thanks again!

np.savetxt('test.txt', SPOT, fmt = '%10.5f', delimiter=',', newline = ';\n', header='data =[...', footer=']', comments = '#') 

Cheers! Sree.

Upvotes: 0

Marcin
Marcin

Reputation: 238189

If you have scipy than you can do:

import scipy.io
scipy.io.savemat('/tmp/test.mat', dict(SPOT=SPOT))

And in matlab:

a=load('/tmp/test.mat');
a.SPOT % should have your data

Upvotes: 1

emesday
emesday

Reputation: 6186

Try scipy.io to export data for Matlab

import scipy.io as sio

matlab_data = dict(SPOT=SPOT)
sio.savemat('data_dump.mat', matlab_data)

data_dump.mat is Matlab data. For more detail, see http://docs.scipy.org/doc/scipy/reference/tutorial/io.html

Upvotes: 2

CT Zhu
CT Zhu

Reputation: 54330

It is not very necessary to write your array into a special format. Write it into a normal csv and use dlmread to open it in matlab.

In numpy side, write your array using np.savetxt('some_name.txt', aar, delimiter=' ')

Upvotes: 2

Related Questions