MATLAB Answers

Convert python numpy array to double

조회 수: 596(최근 30일)
Peter 2014년 10월 4일
댓글: Badr Hisham 2021년 6월 30일 6:57
The plot call below will throw an error because x is not a matlab type. How do you convert a python numpy array to a regular matlab matrix?
x = py.numpy.random.random([4,4]);
Sincerely, Peter
  댓글 수: 3
Peter 2014년 10월 4일
>> x
x =
Python ndarray with properties:
T: [1x1 py.numpy.ndarray]
base: [1x1 py.NoneType]
ctypes: [1x1 py.numpy.core._internal._ctypes]
data: [1x1 py.buffer]
dtype: [1x1 py.numpy.dtype]
flags: [1x1 py.numpy.flagsobj]
flat: [1x1 py.numpy.flatiter]
imag: [1x1 py.numpy.ndarray]
itemsize: 8
nbytes: 128
ndim: 2
real: [1x1 py.numpy.ndarray]
shape: [1x1 py.tuple]
size: 16
strides: [1x1 py.tuple]
[[ 0.84501423 0.72129285 0.53197632 0.56672641]
[ 0.353229 0.40170347 0.99848745 0.74374568]
[ 0.15023563 0.72432396 0.05446134 0.00455388]
[ 0.85040029 0.65360657 0.35074251 0.08965406]]

댓글을 달려면 로그인하십시오.

채택된 답변

David Garrison
David Garrison 2020년 8월 27일
Beginning in MATLAB R2018b, Python functions that accept numpy arrays may also accept MATLAB arrays without explicit conversion. When necessary, a numpy array can be created explicitly from a MATLAB array. For example, if you have a supported version of Python that is installed with the numpy library, you can do the following:
>> x = rand(2,2); % MATLAB array
>> y = py.numpy.array(x); % numpy array
y =
Python ndarray:
0.5943 0.8064
0.6133 0.1372
Use details function to view the properties of the Python object.
Use double function to convert to a MATLAB array.
Also beginning in MATLAB R2018b, it is possible to convert numeric numpy arrays returned from Python into MATLAB arrays. For example:
>> y = py.numpy.random.random([int32(2), int32(2)]) % numpy array
y =
Python ndarray:
0.5943 0.8064
0.6133 0.1372
Use details function to view the properties of the Python object.
Use double function to convert to a MATLAB array.
>> x = 2*double(y) % MATLAB array
x =
1.1885 1.6129
1.2266 0.2744
See the MATLAB documentation on Passing Matrices and Multidimensional Arrays for additional Information.
  댓글 수: 1
Badr Hisham
Badr Hisham 2021년 6월 30일 6:57
I got this error
Conversion to double from cell is not possible.

댓글을 달려면 로그인하십시오.

추가 답변(3개)

Jim Hokanson
Jim Hokanson 2014년 11월 4일
data = double(py.array.array('d',py.numpy.nditer(x))); %d is for double, see link below on types
data = reshape(data,[4 4])'; %Could incorporate x.shape here ...
py.array.array is apparently the way Matlab suggests getting data from Python into Matlab (see link above)
This however requires an iterable over which the array can be constructed, hence the call to nditer()
Once the value is an array, then Matlab has written functionality for casting to a Matlab type, in this case via double.
  댓글 수: 6
Eric Cousineau
Eric Cousineau 2017년 5월 30일
To build further upon y'all's work, I've made a really rough prototype, using `matpy`, to get `numpy`-friendly proxy that allows more natural referencing, indexing / slicing, etc., via `subsref` and `subsassgn`:
Example code:
pyA = py.numpy.eye(3);
mlA = NumPyProxy(pyA);
mlA(3, 2)
sub = mlA([2, 1], 3)
double(sub) % 2017-05-30T01:09-04:00 - Presently a bug, wrong order
sub2 = mlA([1, 2], 3)
mlA([2, 1], 3) = 100 * [1, 2]
mlA(:) = 5
Note that PyProxy also permits casting of >1-D arrays, using `subsref` tricks, whereas MATLAB R2016b presently does not permit passing 2-D matrices (at least, as far as I've tried using other people's examples).
This is an ongoing effort to test some Drake functionality: GitHub Issue
This has only been tested / tinkered with in R2016b, and still needs refinement / robustification.
I will try to see if hacks like this aren't needed in future versions of MATLAB.
Thanks a ton for taking the time to post y'all's stuff!

댓글을 달려면 로그인하십시오.

Shaowu Pan
Shaowu Pan 2017년 9월 27일
편집: per isakson 2017년 9월 27일
Weird discussion...
def npArray2Matlab(x):
return matlab.double(x.tolist())
  댓글 수: 2
timo kvamme
timo kvamme 2019년 1월 2일
Thank you, this worked

댓글을 달려면 로그인하십시오.

Jim Hokanson
Jim Hokanson 2014년 10월 4일
편집: Jim Hokanson 2014년 10월 4일
Here's a very ugly solution.
temp = cellfun(@cell,cell(x.tolist),'un',0);
data = cell2mat(vertcat(temp {:}));
A slightly cleaner solution:
data = typecast(uint8(char(,'double');
data = reshape(data,[4 4])'; %Could incorporate x.shape here ...
Then of course:
Sorry I don't have time to explain how you would know that you need to do these things. I have to run!
  댓글 수: 4
Jim Hokanson
Jim Hokanson 2014년 10월 8일
Interesting. The problem occurs when there is a zero in the underlying raw buffer (not a zero value but a 0 byte). I'm not sure if this desired or if it is a bug.

댓글을 달려면 로그인하십시오.


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by