matlab - 如何在Matlab中像在python和js中一样创建 'closure function'?

标签 matlab function closures

背景

在 Python 和 JS 中,我们有闭包,它返回一个带有一些预定义变量的函数。例如

def make_printer(msg):
    def printer():
        print msg
    return printer

Matlab 中有类似的东西吗?

这里我有一个回调函数

function show(object, eventdata)

这将被设置为我的 GUI 的回调

func = @show;
set(gcf, 'WindowButtonMotionFcn', func);

但是,我想向此 show 函数添加一些附加参数。

目前我正在使用全局变量来做到这一点。但我认为如果我们有一个“闭包函数”就会很优雅。

关于匿名函数

是的,Matlab 中确实有匿名函数。不过我觉得它太简单了,无法支持60行程序。

最佳答案

曾经有一份由谢尔盖·西马科夫(Sergey Simakov)撰写的文件在互联网上流传。它非常简洁,不是特别描述性的,但涵盖了基础知识。根据我的经验,这是关于 matlab GUI 的最权威的文本。我怀疑它仍然是......

您正在解决两个/三个问题:

关闭问题

嵌套函数解决了这个问题。

function iterator = count(initial)
 % Initialize
 if ~exist('initial','var')
  counter = 0
 else
  counter = initial
 end
 function varargout = next() % [1] 
  % Increment
  counter = counter + 1
  varargout = {counter}      % [1] 
 end
 iterator = @next
end

注释:

  1. 一个人不能简单地返回柜台!它必须包装在 varargout 中或分配给其他输出变量。

用法

counter = count(4) % Instantiate
number = counter() % Assignment
number = 
  5

封闭范围+状态问题

没有难看的大括号,不用担心范围、字符串元胞数组。如果您需要访问 SELF 下的某些内容,则不再需要 FINDOBJ、USERDATA、SET/GETAPPDATA、GLOBAL 等废话。

classdef Figure < handle

 properties 
  parent@double
  button@double
  label@double
  counter@function_handle
 end

 methods 
  function self = Figure(initial)
   self.counter = count(initial) % [1]
   self.parent  = figure('Position',[200,200,300,100])
   self.button  = uicontrol('String','Push',          'Callback', @self.up, 'Style', 'pushbutton', 'Units', 'normalized', 'Position', [0.05, 0.05, 0.9, 0.4])
   self.label   = uicontrol('String', self.counter(),                       'Style', 'text',       'Units', 'normalized', 'Position', [0.05, 0.55, 0.9, 0.4])
  end

  function up(self,comp,data)
   set(self.label,'String',self.counter())
  end
 end
end

注意:

  1. 其中一个使用上面闭包问题中列出的函数

用法:

f = Figure(4)                  % Instantiate
number = get(f.label,'String') % Assign
number = 
  5

您可能更喜欢:

f.label.get('String')          % Fails (f.label is double not handle, go figure)
h = handle(f.label)            % Convert Double to handle
number = h.get('String')       % Works 
number = 
  5

关于matlab - 如何在Matlab中像在python和js中一样创建 'closure function'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22624944/

相关文章:

javascript - 函数标题变量

javascript - JS中变量的作用域

matlab - 使用 `text` 绘图时如何包装字符串?

matlab - 我如何在 Eigen 应用类似 bsxfun 的功能?

c++ - 虚函数编译优化c++

javascript - jQuery 闭包 : How to get a value from a function click

iOS Swift 传递关闭作为属性?

arrays - 最小化Matlab中数组列的总和

matlab - 验证相机校准仍然有效

c++ - 使用相同功能时意外收到 "std::out_of_range"错误