Search code examples
javamatlabmatlab-deploymentmatlab-compiler

how to compile class with matlab compiler sdk?


i would like to compile a java package from matlab code. i have a class in matlab:

classdef MyClass 
   properties
      Prop1
   end
   events
      Event1
   end
   methods
      function obj = MyClass()   // no arguments
         if nargin > 0
            obj.Prop1 = arg;
         end
      end
   end
end

i tried to compile it but it doesnt work. Its not possible to compile classes. SO i try to write wrapper functions. In my Wrapper function i call my classdef script as and return the object. I could compile this function but in java i need to pass arguments.But my class constructor in matlab has no arguments.

in Java i have a Class1 and i create a new objects of it. This Object now give me access to my contructor:

Class1 matlabClassTest = new Class1();
matlabClassTest.MyClass(???); // her it ask for arguments

Solution

  • it is necessary to wrap the functions of the class because matlab compiler sdk can only compile functions.

    If this is the class:

    classdef MyClass 
       properties
          Prop1
       end
    
       methods  
         function obj= doSomething(obj,x)
          obj.Prop1=x;
          end
       end
    end
    

    create a new m. file for your constructor Wrapper function. This function returns an object of the class.

    function obj=createMyClassObject()
    obj=MyClass();
    end
    

    create a new m. file with your wrapper function The Wrapper function returns the obj passed as argument.

    function obj= doSomethingWrapper(obj,x)    
    obj.doSomething(x)
    end
    

    Compile both functions with Matlab Compiler SDK. The class Myclass m File should be also in the same directory. Matlab Compiler SDK recognizes the dependency automatically and shows it in the compiler options.

    In Java you can now call the createMyClassObject() function and you will receive the Matlab object. Pass this Object to the doSomethingWrapper() function.