2014-06-23 56 views
0

假設有一個最簡單的matlab struct包含多個變量和函數處理函數。我需要將此函數處理程序綁定到其他結構的字段,以便處理程序能夠更改這些變量。將matlab結構的函數字段與其他結構的字段綁定

事情是這樣的:

function newStruct = createStruct() 

    newStruct.input = unifrnd(-1, 1, [9 9]); 
    newStruct.kernel = unifrnd(-1, 1, [7 7]); 
    newStruct.output = zeros(3, 3); 

    function f() 
     newStruct.output = conv2(newStruct.input, newStruct.kernel, 'valid'); 
    end  

    newStruct.fnc = @f; 
end 

strct = createStruct(); 
strct.fnc(); 

它不工作,但是這是可以實現?

+0

什麼版本的Matlab的您使用的是? –

+0

@ CST-Link,R2013a 64-linux – gorill

回答

2

你似乎在做的是嘗試使用Matlab以面向對象的方式工作。 Matlab的最新版本接受特殊的語法來聲明類。例如,您的代碼將被重寫(代碼需要在具有相同名稱的類文件,即MyClass.m):

classdef MyClass < handle 

    properties 
     input; 
     kernel; 
     output; 
    end; 

    methods 
     function obj = MyClass() 
      input = unifrnd(-1, 1, [9 9]); 
      kernel = unifrnd(-1, 1, [7 7]); 
      output = zeros(3, 3); 
     end 

     function f(obj) 
      obj.output = conv2(obj.input, obj.kernel, 'valid'); 
     end 
    end; 
end; 

然後你就可以實例化和修改你的對象,如:

my_obj = MyClass(); 
my_obj.f(); 
disp my_obj.output; 

更多細節在這裏:http://www.mathworks.com/help/matlab/object-oriented-programming.html

1

@CST-LinkOutput自動更新,使用Dependent關鍵字:

classdef MyClass < handle 

    properties   
     Input = unifrnd(-1, 1, [9 9]); 
     Kernel = unifrnd(-1, 1, [7 7]); 
    end 

    properties (Dependent)   
     Output;   
    end 
    methods   
     function [output] = get.Output(this) 
      output = conv2(this.Input, this.Kernel, 'valid'); 
     end 
    end 

end 

這可以這樣使用:

obj = MyClass(); 
obj.Output; % No need to call `f` before to get `Output` value