ส่งกลับตัวแปรจาก python ไปยัง Matlab
Oct 08 2020
ฉันพยายามส่งผ่านตัวแปรบางตัวจาก python ไปยัง Matlab แต่ฉันไม่ได้จัดการ ถ้าฉันส่งผ่านตัวแปรเพียงตัวเดียวก็ใช้ได้ดี แต่เนื่องจากฉันต้องส่งผ่านตัวแปรเพิ่มเติมด้วยประเภทต่างๆ (เมทริกซ์เวกเตอร์สเกลาร์) จึงไม่ทำงาน
นี่คือรหัสของฉันใน 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
และนี่คือสคริปต์ matlab ที่จะอ่าน:
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)));
คำตอบ
Paolo Oct 08 2020 at 14:59
ฟังก์ชันของคุณส่งคืนทูเพิล:
>> p = py.file_return.run_test_return;
>> class(p)
py.tuple
และองค์ประกอบในทูเปิลเป็นประเภทข้อมูลที่แตกต่างกัน:
>> class(p{1})
py.numpy.ndarray
>> class(p{3})
py.int
ใน MATLAB คุณสามารถห่อทูเปิลไว้ในเซลล์แล้ววนซ้ำด้วย cellfun เพื่อแปลงทุกองค์ประกอบให้เป็นอาร์เรย์ของเซลล์เป็นสองเท่า:
>> c=cellfun(@double,cell(p),'UniformOutput',false);