3

I am calling from matlab (R2015b) a python module that I created. Now I've noticed that, we can only send to python a 1xN vector.

So I fixed this in Matlab

Matlab Code:

a = ones(3, 3);
a = a(:).';

Then I sent a as parameter to python function.

 m = py.computeCoreset.computecoreset(a, obj.coresetSize);

Now my problem that python doesn't return Matlab matrix I noticed that I am returning an ndarray while debugging.

This is my python code:

import numpy as np


def computecoreset(mat, coresetSize):
    return np.random.choice(mat, coresetSize)

I guess I need to make the ndarray a matrix once again

But how do I convert it ?

Thanks in advance!

2
  • What happens when you use the function that you show? Oct 27, 2016 at 23:45
  • Your Python code obviously returns a numpy array, but doesn't the interface code create some sort of MATLAB object from that? A numpy array can't exist in a MATLAB environment. Elaborate on how you call the Python code from MATLAB.
    – hpaulj
    Oct 27, 2016 at 23:46

3 Answers 3

6

https://www.mathworks.com/matlabcentral/answers/157347-convert-python-numpy-array-to-double

The accepted answer suggests py.array.array function:

data = double(py.array.array('d',py.numpy.nditer(x)));

Which is also listed on

https://www.mathworks.com/help/matlab/matlab_external/handling-data-returned-from-python.html

1
  • I think the point of using nditer(x) is to serialize the elements of x into a 1-d sequence. In this case, x is 1-d, so I don't think using nditer() is necessary. Oct 28, 2016 at 2:42
2

This is a shot in the dark, because I don't have Matlab to test it, but I suspect you'll have to return a python array object, not a numpy array. So something like this:

import numpy as np
import array


def computecoreset(mat, coresetSize):
    c = np.random.choice(mat, coresetSize)
    return array.array('d', c)
1

Just for completeness, the other way goes like this:

rnd = rand(5);
py.numpy.asarray(rnd)


  Python ndarray:

    0.3112    0.6541    0.2290    0.9961    0.0046
    0.5285    0.6892    0.9133    0.0782    0.7749
    0.1656    0.7482    0.1524    0.4427    0.8173
    0.6020    0.4505    0.8258    0.1067    0.8687
    0.2630    0.0838    0.5383    0.9619    0.0844

    Use details function to view the properties of the Python object.

    Use double function to convert to a MATLAB array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.