Skip to content

Python 3.9 breaks mat2ndarray.m #39

Description

@andykee

Using mat2ndarray results in the following error:

Python Error: AttributeError: 'array.array' object has no attribute 'fromstring' 

From this post, the issue appears to be due to the fact that MATLAB is attempting to pass the contents of an array to Numpy by calling by using Python's fromstring() method, which was deprecated in Python 3.9.

There appears to be a workaround by using MATLAB's (undocumented) getByteStreamFromArray() method:

% Create some array
a = round(10*rand(2,3,4));

% Grab raw bytes
b = getByteStreamFromArray(a);

% Grab its shape
msize = size(a);

% Hardcoded header size found empirically (maybe should find some doc to
% justify this)
header = 72;

% Create numpy array from raw bytes buffer
d = py.numpy.frombuffer(b(header+1:end)).reshape(int32(msize));

One additional complication is in appropriately sizing the header. A quick test showed that the header size depends on the number of array dimensions:

0D, 1D, 2D: 64 bytes
3D, 4D: 72 bytes
5D, 6D: 80 bytes
...

The header size can be computed as 64 + (ceil(ndim/2) - 1)*8. Note that this is still valid for what Numpy would call a 0-dimensional "array" since MATLAB's ndims() function always computes the number of dimensions as greater than or equal to 2.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions