2016-04-09 34 views
0

我正在被上不同模式基于诸如在选择的采样速率滤波器组延迟的东西,改变模型参数等构成的Simulink模型...转换类属性STRUCT尊重能见度

我虽然设置了所有参数在ParameterStruct,然后加载适当的参数结构为每个模式。

这类映射很好地与具有从属属性的类相匹配,因为只有几个输入会生成很多模型参数。

但是,当我尝试生成从一个class知名度的struct的不尊重:

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: [] 

这是不能接受的,因为我需要的结构导出到C算账,以便能够从生成的代码动态地设置模式。

回答

1

你可以覆盖默认struct为类:

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 

现在:

>> obj = SquareArea 
obj = 
    SquareArea with properties: 

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

请注意,您仍然可以通过显式调用内建一个得到原来的行为:

>> 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 
1
publicProperties = properties(x); 
myStruct = struct(); 
for iField = 1:numel(publicProperties), myStruct.(publicProperties{iField}) = []; end 
0

结合Amro的答案& DVarga,默认的结构函数可以推广:

 function s = struct(self) 
     publicProperties = properties(self); 
     s = struct(); 
     for fi = 1:numel(publicProperties) 
      s.(publicProperties{fi}) = self.(publicProperties{fi}); 
     end     
    end