曾经有一个由谢尔盖·西马科夫(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
注意事项:
- 不能简单地返回计数器!它必须包含在 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
注意事项:
- 使用上面闭包问题中列出的函数
用法:
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