1

I have testPython.py :

import numpy as np
def numpyTest():
    print("Testing numpy...")
    x = np.array([1,2,3])
    return x

and I have test.m:

clear; clc;

value = py.testPython.numpyTest()

When I run test.m I get:

Testing numpy...

value = 

  Python ndarray with properties:

           T: [1×1 py.numpy.ndarray]
        base: [1×1 py.NoneType]
      ctypes: [1×1 py.numpy.core._internal._ctypes]
        data: [1×24 py.buffer]
       dtype: [1×1 py.numpy.dtype]
       flags: [1×1 py.numpy.flagsobj]
        flat: [1×1 py.numpy.flatiter]
        imag: [1×1 py.numpy.ndarray]
    itemsize: 8
      nbytes: 24
        ndim: 1
        real: [1×1 py.numpy.ndarray]
       shape: [1×1 py.tuple]
        size: 3
     strides: [1×1 py.tuple]

    [1 2 3]

How do I convert python numpy array to matlab matrix?

MoneyBall
  • 2,343
  • 5
  • 26
  • 59
  • Why not work entirely in Python? (https://stackoverflow.com/a/17535694/1959808) What benefit is there in using Matlab? – 0 _ Oct 31 '17 at 10:55
  • @IoannisFilippidis the only reason for using matlab is because I have matlab code that controls ROS and gazebo. I want to use deep learning tools like tensorflow and pytorch AND connect that to gazebo and ROS via matlab – MoneyBall Oct 31 '17 at 10:56
  • have you tried accessing `value`? e.g. `value(1)` – Ander Biguri Oct 31 '17 at 11:19
  • @AnderBiguri Yep. it doesn't work since it's python ndarray. – MoneyBall Oct 31 '17 at 12:15
  • There must be something, the output you show clearly shows `[1 2 3]` in the end – Ander Biguri Oct 31 '17 at 12:18
  • @AnderBiguri Yes I see that as well. But I'm not sure which properties or methods I need to use to get `[1 2 3]`... – MoneyBall Oct 31 '17 at 12:19
  • Since ROS isn't written in Matlab, and ROS has good support in Python, translating the Matlab code to Python is a simple long-term solution. – 0 _ Oct 31 '17 at 15:16

1 Answers1

1

We have to perform few conversions here:

clear; clc;

value = py.testPython.numpyTest();% ndarray
pyList = value.tolist(); % ndarray -> pylist
result = cellfun(@double,cell(pyList)) %pylist-> cell array -> double array

Another option is to transfer data via file, but I don't like it.

And a link to Matlab Docs about Python list conversion:

https://www.mathworks.com/help/matlab/matlab_external/use-python-list-of-numeric-types-in-matlab.html

Pavel Oganesyan
  • 6,774
  • 4
  • 46
  • 84