How to access class and functions from python

39 views (last 30 days)
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'.

Accepted Answer

Siddharth Bhutiya
Siddharth Bhutiya on 21 Sep 2018
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 Comment
Arshad Pasha
Arshad Pasha on 28 Sep 2018
Edited: Arshad Pasha on 28 Sep 2018
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

Sign in to comment.

More Answers (0)

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!