1

I need to use an object among several functions on a Matlab S-Function. The object is used as a library and it is needed to set the conection with a server, get data from it in each loop and close it at the end of simulation. The use of the object its something like this:

ClassX ObjectX;

[Handle clientID]=ObjectX.setConnection(...);

while(coonection)
 [result]=ObjectX.getPosition(Handle ClientID,...);
 [result]=ObjectX.getAngle(Handle ClientID,...);
 ...
end

[result]=ObjectX.CloseConnection(...);

Its not convinient to instance and close the comunication in every loop. So I whant to create the object and set the conection on "function setup(block)", update data on "function Update(block)" and close the conection on "function Terminate(block)" but to do this I need to share the "ObjectX" an "clientID" among the functions.

I hope you can help me.

am304
  • 13,758
  • 2
  • 22
  • 40
DdS
  • 11
  • 3

1 Answers1

1

You can use a Singleton class, which is instantiated once and returns the same instance everytime you ask for it.

classdef (Sealed) SingleInstance < handle
   methods (Access = private)
      function obj = SingleInstance
      end
   end

   methods (Static)
      function singleObj = getInstance
         persistent localObj
         if isempty(localObj) || ~isvalid(localObj)
            localObj = SingleInstance;
         end
         singleObj = localObj;
      end
   end

   method (Access = public)
       function setup(obj, block)
       end
       function update(obj, block)
       end
       function terminate(obj, block)
       end
   end
end

More information is available here

Kavka
  • 4,191
  • 16
  • 33
  • Hi! thaks! My goal is to comunicate MAtlab with a robotic simulator (Vrep) the fabricant provides the class and entry system to work with it, since I hope I have not to modified it because I not shure how it works. This library was designed to be used in a .m or in a function but not in simulink or s-function. So i hope you can help me to use it without modification. – DdS Apr 04 '14 at 13:05
  • You should be able to use the Singleton class to wrap the class that does the communication without modifying the class itself. In the singleton constructor `SingleInstance` you would call `ObjectX.setConnection` to initialize the connection. The next time you call `getInstance`, you would just get a handle of the existing instance without re-initializing the connection. You should probably read more about the MATLAB class system to familiarize yourself with it. – Kavka Apr 04 '14 at 14:42