Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python 3.9 breaks mat2ndarray.m #39

Open
andykee opened this issue Mar 3, 2022 · 2 comments
Open

Python 3.9 breaks mat2ndarray.m #39

andykee opened this issue Mar 3, 2022 · 2 comments

Comments

@andykee
Copy link
Owner

andykee commented Mar 3, 2022

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.

@andykee
Copy link
Owner Author

andykee commented Mar 3, 2022

It turns out the above approach doesn't work in Python 3.9 either. More details here.

@andykee
Copy link
Owner Author

andykee commented Oct 27, 2023

This is actually an incompatibility between Python and MATLAB versions. Numpy arrays seem to be supported now, as long as version compatibility is achieved. The version compatibility guide is at https://www.mathworks.com/support/requirements/python-compatibility.html?s_tid=srchtitle_site_search_1_python

This is really a documentation issue rather than a software bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant