Created
February 5, 2020 23:21
-
-
Save mgronhol/511d8288a9cef3f1b184f94d24de0f96 to your computer and use it in GitHub Desktop.
Generate mat-file containing a 2D array of doubles.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import struct | |
miINT8 = 1 | |
miINT32 = 5 | |
miUINT32 = 6 | |
miDOUBLE = 9 | |
miMATRIX = 14 | |
mxDOUBLE_CLASS = 6 | |
def gen_header( description = "" ): | |
description = "MATLAB 5.0 MAT-file " + description | |
header = bytes( description, "utf-8" ) | |
if len( header ) < 116: | |
header += struct.pack("B", 0) * (116 - len(header)) | |
header += struct.pack( "8B", *([0]*8) ) | |
header += struct.pack( ">H2s", 0x0100, bytes( "MI", "ascii" ) ) | |
return header | |
def encode_row( values ): | |
out = struct.pack( ">II", miDOUBLE, len(values)*8 ) | |
out += struct.pack( ">%id" % len(values), *values ) | |
return out | |
def gen_array( values, name = "array" ): | |
out = struct.pack( ">IIII", miUINT32, 8, mxDOUBLE_CLASS, 0 ) | |
out += struct.pack( ">IIII", miINT32, 8, len( values ), len( values[0] ) ) | |
padding = 8 - len( name ) | |
out += struct.pack( ">II", miINT8, len( name ) ) | |
out += bytes( name, "utf-8" ) | |
if padding > 0: | |
out += struct.pack( "B", 0 ) * padding | |
single_row = [] | |
for row in values: | |
single_row.extend( row ) | |
out += encode_row( single_row ) | |
array_header = struct.pack( ">II", miMATRIX, len( out ) ) | |
return array_header + out | |
def generate_mat( values, name = "array", description = "" ): | |
return gen_header( description ) + gen_array( values, name ) | |
def write_mat( fname, values, name = "array", description = "" ): | |
with open( fname, 'wb' ) as handle: | |
handle.write( generate_mat( values, name, description ) ) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment