필터 지우기
필터 지우기

How to access class and functions from python

조회 수: 24 (최근 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 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