2016-04-09 33 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