Search code examples
matlaboopstructclass-visibility

Converting class properties to struct respecting visibility


I'm working on a simulink model that is configured on different modes that change the model parameters based on the stuff like the chosen sample rate filter group delay, etc...

I though of setting all the parameters on a ParameterStruct, then load the proper parameter struct for each mode.

This sort of maps well to a class with Dependent properties because, there are a lot of model parameters that are generated from only a couple inputs.

But when I try to generate an struct from the a class visibility is not respected:

classdef SquareArea
   properties
      Width
      Height
   end
   properties (Access =private)
      Hidden
   end
   properties (Dependent)
      Area
   end
   methods
      function a = get.Area(obj)
         a = obj.Width * obj.Height;
      end
   end
end
>> x=SquareArea

x = 

  SquareArea with properties:

     Width: []
    Height: []
      Area: []

>> struct(x)
Warning: Calling STRUCT on an object prevents the object 
from hiding its implementation details and should thus
be avoided. Use DISP or DISPLAY to see the visible public
details of an object. See 'help struct' for more information.

ans = 

     Width: []
    Height: []
    Hidden: []
      Area: []

This is not acceptable, because I need to export the struct to C afterwards, to be able to set the mode dynamically from the generated code.


Solution

  • You could override the default struct for your class:

    classdef SquareArea
       properties
          Width = 0
          Height = 0
       end
       properties (Access=private)
          Hidden
       end
       properties (Dependent)
          Area
       end
       methods
          function a = get.Area(obj)
             a = obj.Width * obj.Height;
          end
          function s = struct(obj)
              s = struct('Width',obj.Width, 'Height',obj.Height, 'Area',obj.Area);
          end
       end
    end
    

    Now:

    >> obj = SquareArea
    obj = 
      SquareArea with properties:
    
         Width: 0
        Height: 0
          Area: 0
    >> struct(obj)
    ans = 
         Width: 0
        Height: 0
          Area: 0
    

    Note that you can still get the original behavior by explicitly calling the builtin one:

    >> builtin('struct', obj)
    Warning: Calling STRUCT on an object prevents the object from hiding its implementation details and should
    thus be avoided. Use DISP or DISPLAY to see the visible public details of an object. See 'help struct' for
    more information. 
    ans = 
         Width: 0
        Height: 0
        Hidden: []
          Area: 0