1

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.

2
  • 2
    Please edit your question by adding this code to it. Nothing can be done with it as a comment Commented Jul 1, 2014 at 4:24
  • What do the first few lines of data_dump.txt look like? You can probably read it into Matlab as is. Commented Jul 1, 2014 at 5:22

4 Answers 4

2

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=' ')

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks everyone! @CT Zhu: I tried using np.savetxt now 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 = '#')
2

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

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.