How to access class and functions from python

26 次查看(过去 30 天)
Hello All,
I am trying to access matlab code in python. I have referred ref1 and ref2 I am able to work with single function code, but not with a multi function code as mentioned in ref2 or even this basic example
classdef Test1
properties (Access = private)
input1 = 0;
input2 = 0;
end
methods
function out1 = ADD_1(this,i1,i2)
this.input1 = i1;
this.input2 = i2;
out1 = this.input1 + this.input2;
end
function out2 = SUB_1(this,out1)
out2 = out1 - 1;
end
end
end
What I have tried is
import matlab.engine
eng = matlab.engine.start_matlab()
eng.addpath(r'C:\Users\Python_file_test', nargout=0);
func1_out = eng.ADD_1(10,20)
I get an error
MatlabExecutionError: Undefined function 'ADD_1' for input arguments of type 'int64'.

采纳的回答

Siddharth Bhutiya
Siddharth Bhutiya 2018-9-21
Whenever you create a class in MATLAB it will be a Value class by default. However, while working with MATLAB Engine for python you can only use MATLAB Handle classes, which is mentioned in the link below
So in order to make the above example work, you will have to make your class a handle class which can be done by replacing the first line of your MATLAB code to
classdef Test1 < handle
Another thing to note here is that the function signature of ADD_1 indicates that it needs 3 inputs: Test1 Object(this), first number(i1) and second number(i2). So inside your python script, you will have to create an object for Test1 and pass it as the first argument of ADD_1
myobj = eng.Test1()
func1_out = end.ADD_1(myobj, 10, 20)
I believe that the above changes should resolve your issue.
  1 个评论
Arshad Pasha
Arshad Pasha 2018-9-28
编辑:Arshad Pasha 2018-9-28
Hey Siddhart, thank you, that worked. Just a follow up question, how to handle the recursive functions, let's say a function is called every 1 second in matlab, can I monitor that or call that via python similar to what you have suggested previously. just to simplify, want to call the ADD_1 function 10 times in a loop via python.
classdef Test1 < handle
properties (Access = private)
input1 =0;
input2 = 0;
end
methods
function out1 = ADD_1(this,i1,i2)
this.input1 = i1;
this.input2 = i2;
out1 = this.input1 + this.input2;
end
function out2 = SUB_1(this,out1)
out2 = out1 - 1;
end
end
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call MATLAB from Python 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by