Trả về các biến từ python sang Matlab

Oct 08 2020

Tôi đang cố chuyển một số biến từ python sang Matlab, nhưng tôi không quản lý được. Nếu tôi chỉ truyền một biến thì nó hoạt động tốt, nhưng vì tôi cần chuyển nhiều biến hơn với các kiểu khác nhau (ma trận, vectơ, vô hướng) thì không hoạt động.

đây là mã của tôi trong Python test_return.py:

import numpy as np
def run_test_return():
    a = np.ones((5,3))
    b = np.ones((10))
    c = 4
        
    return a, b, c 
# I don't know if I should return the variables as tuples,list, dictionary... to be easier to read in matlab

Và đây là tập lệnh matlab để đọc:

pyOut = py.importlib.import_module('test_return');

py.importlib.reload(pyOut);

[a,b,c] = py.test_return.run_test_return(); % This is the part that doesn't work, I don't know how to import more than one variable, if I import only one works fine...

a = double(py.array.array('d',py.numpy.nditer(a))); % I don't know if this is the best way to read numpy 2D array

b = double(py.array.array('d',py.numpy.nditer(a)));

c = double(py.array.array('d',py.numpy.nditer(a)));

Trả lời

Paolo Oct 08 2020 at 14:59

Hàm của bạn trả về một bộ giá trị:

>> p = py.file_return.run_test_return;
>> class(p)
py.tuple

và các phần tử trong tuple thuộc các kiểu dữ liệu khác nhau:

>> class(p{1})
py.numpy.ndarray

>> class(p{3})
py.int

trong MATLAB, bạn có thể chỉ cần bọc tuple trong một ô và lặp lại nó bằng cellfun để chuyển đổi mọi phần tử thành một mảng ô nhân đôi:

>> c=cellfun(@double,cell(p),'UniformOutput',false);