将 matlab 结构体的函数字段与其他结构体的字段绑定



假设有一个最简单的matlab struct,它有几个变量和函数处理程序。我需要将这个函数处理程序绑定到其他结构的字段,以便处理程序能够更改这些变量。

像这样:

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();

它不工作,但这是可能实现的吗?

您似乎要做的是尝试以面向对象的方式与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

与@CST-Link相同,自动更新Output,使用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

最新更新