Save an array as bin in Matlab, pass it to Python and read the bin file in Python
Question: I am currently trying to save an array as bin file in Matlab, send it to
Python and read it in Python. However, Matlab is showing errors when I run it.
I am using the following codes:

Read the array in Matlab, convert to bin file and pass 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
    

squared.py file:

    
    
    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 gets printed. I guess that the bin
file is not getting passed properly to the squared.py file.

Thanks for your feedback.

Nazmul


Answer: There are several problems here.

  1. You should use double underscore when checking for 'main'. I.e. `__main__ == "__main__"`.
  2. You are _not_ collecting bytes but rather always storing the _last_ byte read. Therefore, the last byte is always `""`.
  3. Finally, it seems like indentation is not correct. I assume this is just a stackoverflow formatting error.
  4. One more potential issue - When you use fwrite(fid, A) in MATLAB, it assumes that you want to write bytes (8 bit numbers). However, your `rand()` command generates reals, so MATLAB first rounds the results to integers and your binary file will hold '0' or '1' only.

Final note: Reading a file one byte at a time is probably very inefficient. It
is probably better to read the file in large chunks, or - if it is a small
file - read the entire file in one `read()` operation.

The corrected Python code is as follows:

    
    
    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;
    

