Convert python numpy array to double
129 ビュー (過去 30 日間)
古いコメントを表示
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]);
plot(x)
Sincerely, Peter
3 件のコメント
採用された回答
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.
3 件のコメント
abraham rodriguez
2021 年 9 月 18 日
@Badr Hisham In latest R2021a, you can pass directly a numpy ndarray to double() and it will convert to a native matlab matrix.
winkmal
2022 年 5 月 17 日
y = py.numpy.random.random([int32(2), int32(2)])
gives
Python Error: AttributeError: 'array.array' object has no attribute 'fromstring'
その他の回答 (3 件)
Jim Hokanson
2014 年 11 月 4 日
Here's another approach. This is alluded to by http://www.mathworks.com/help/matlab/matlab_external/handling-data-returned-from-python.html
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) https://docs.python.org/2/library/array.html
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 件のコメント
Dev-iL
2017 年 5 月 16 日
編集済み: Dev-iL
2017 年 5 月 16 日
Hi Christoph,
Thanks for the code! However, it doesn't support the conversion of scalar arrays:
Error using reshape
Size vector must have at least two elements.
Error in matpy.nparray2mat (line 55)
result=reshape(result,fliplr(data_size));
This can be solved by modifying the first `if` statement in nparray2mat to:
if any(numel(data_size) == [0,1])
Cheers!
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(:)
double(mlA(:))
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)
double(sub2)
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 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
2017 年 9 月 27 日
編集済み: per isakson
2017 年 9 月 27 日
Weird discussion...
def npArray2Matlab(x):
return matlab.double(x.tolist())
2 件のコメント
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(x.flat.base.data)),'double');
data = reshape(data,[4 4])'; %Could incorporate x.shape here ...
Then of course:
plot(data)
Sorry I don't have time to explain how you would know that you need to do these things. I have to run!
Jim
4 件のコメント
Peter
2014 年 10 月 6 日
編集済み: Peter
2014 年 10 月 6 日
Jim, it's a bit complicated. For example, if I run:
for jj = 1:10
x = py.numpy.random.random([10,10]);
try
data = typecast(uint8(char(x.flat.base.data)),'double');
disp(numel(data))
catch me
warning(me.message)
end
end
I should get 100 doubles, but I end up with something very different:
Warning: The first input must contain a multiple of 8 elements to convert from uint8 (8 bits) to double (64 bits).
29.00
8.00
7.00
10.00
Warning: The first input must contain a multiple of 8 elements to convert from uint8 (8 bits) to double (64 bits).
24.00
20.00
Warning: The first input must contain a multiple of 8 elements to convert from uint8 (8 bits) to double (64 bits).
56.00
Do you have any idea why the typecasting is broken? I would guess that it's something to do with the conversion from the flat.base to char.
Peter.
Jim Hokanson
2014 年 10 月 8 日
編集済み: 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.
参考
カテゴリ
Help Center および File Exchange で Call Python from MATLAB についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!