How to access class and functions from python

42 ビュー (過去 30 日間)
Arshad Pasha
Arshad Pasha 2018 年 9 月 18 日
編集済み: Arshad Pasha 2018 年 9 月 28 日
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 Center および File ExchangeCall 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