2

I am new to both Matlab and Python and I have to convert a program in Matlab to Python. I am not sure how to typecast the data after reading from the file in Python. The file used is a binary file.

Below is the Matlab code:

fid = fopen (filename, 'r');
 fseek (fid, 0, -1);
 meta = zeros (n, 9, 'single');
 v = zeros (n, 128, 'single');
 d = 0;
 for i = 1:n
   meta(i,:) = fread (fid, 9, 'float');
   d = fread (fid, 1, 'int');
   v(i,:) = fread (fid, d, 'uint8=>single');
 end

I have written the below program in python:

fid = open(filename, 'r')
fid.seek(0 , 0)
meta = np.zeros((n,9),dtype = np.float32)
v = np.zeros((n,128),dtype = np.float32)

for i in range(n):
  data_str = fid.read(9);
  meta[1,:] = unpack('f', data_str)

For this unpack, I getting the error as

"unpack requires a string argument of length 4"

. Please suggest someway to make it work.

1
  • You should check out this thread: stackoverflow.com/questions/3162191/…. Not necessarily hard, but quite a challege for a beginner in both languages. Commented Oct 24, 2015 at 15:35

1 Answer 1

0

I looked a little in the problem mainly because I need this in the near future, too. Turns out there is a very simple solution using numpy, assuming you have a matlab matrix stored like I do.

import numpy as np

def read_matrix(file_name):
    return np.fromfile(file_name, dtype='<f')  # little-endian single precision float

arr = read_matrix(file_path)

print arr[0:10]  #sample data
print len(arr)  # number of elements

The data type (dtype) you must find out yourself. Help on this is here. I used fwrite(fid,value,'single'); to store the data in matlab, if you have the same, the code above will work. Note, that the returned variable is a list; you'll have to format it to match the original shape of your data, in my case len(arr) is 307200 from a matrix of the size 15360 x 20.

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

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.