Save the array as bin in Matlab, pass it to Python and read the bin file in Python

I'm currently trying to save an array as a bin file in Matlab, send it to Python and read it in Python. However, when I run it, Matlab shows errors. I use the following codes:

Read the array in Matlab, convert to bin file and go to Python:

array1 = rand(5,1); %% array1 is the desired array that needs to be sent to Python

fid = fopen('nazmul.bin','wb'); %% I want to save array1 in the nazmul.bin file

fwrite(fid,array1);

status=fclose(fid);

python('squared.py','nazmul.bin'); %% I want to send the parameters to squared.py program

file squared.py:

import sys

if __name__ == '__main__':
f = open("nazmul.bin", "rb")   # Trying to open the bin file

try:

   byte = f.read(1)       # Reading the bin file and saving it in the byte array

   while byte != "":

   # Do stuff with byte.

       byte = f.read(1)

   finally:

       f.close()

   print byte                # printing the byte array from Python

However, when I run this program, nothing is printed. I think the bin file is not getting the squared.py file properly.

Thanks for your feedback.

Nazmul

+3
source share
1 answer

There are several issues here.

  • When checking for "main", use the double underscore. That is __main__ == "__main__".
  • , . , "".
  • , , . , stackoverflow.
  • . fwrite (fid, A) MATLAB, , (8- ). rand() , MATLAB , "0" "1".

: , , . , , - - read().

Python :

if __name__ == '__main__':
   f = open("xxx.bin", "rb")   # Trying to open the bin file

   try:
     a = [];
     byte = f.read(1)       # Reading the bin file and saving it in the byte array
     while byte != "":
       a.append(byte);
       # Do stuff with byte.
       byte = f.read(1)

   finally:
       f.close()

   print a;
+4

All Articles