Skip to content

Instantly share code, notes, and snippets.

@trim21
Created September 18, 2023 12:02
Show Gist options
  • Save trim21/934bb2832501f1f580580feff883c7ab to your computer and use it in GitHub Desktop.
Save trim21/934bb2832501f1f580580feff883c7ab to your computer and use it in GitHub Desktop.
matlab `fread` in python with numpy
from typing import Union, BinaryIO
import numpy as np
from binary_reader import BinaryReader
def f_read(reader: Union[BinaryIO, BinaryReader], shape, dtype):
"""
``fread`` method in matlab
"""
size = int(np.iinfo(dtype).bits / 8)
if isinstance(shape, (list, tuple)):
count = shape[0] * shape[1]
b = reader.read(int(size * count))
return np.frombuffer(b, dtype, count=count).reshape(shape, order="F")
return np.frombuffer(reader.read(size * shape), dtype, count=shape)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment