MATLAB: Matlab Programmed GUI data not updated

matlab gui without guideprogrammed matlab gui

I have a very simple question: how to update GUI data using programmed GUI (without GUIDE). The following is my code:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Matlab GUI without Guide
% 05/15/2012
function simpleGui
clear all;
close all;
clc;
h.counter = 0;
h.fig = figure('position',[1000,500,210,60]);
h.button = uicontrol('style','pushbutton',...
'position',[10,10,100,40],...
'string','button');
set(h.button,'callback',{@increment,h});
function increment(hObject,eventdata,h)
h.counter = h.counter + 1;
set(h.button,'string',num2str(h.counter));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Basically I want to display the value of h.counter on the button. I thought I was incrementing h.counter every time h.button is pressed so I expected 1,2,3,4… showing on the button as I clicked, but h.counter was always 1. Why was h.counter not updated?
Any suggestions?
Yunde

Best Answer

The "h" structure that gets captured in the set() of the callback, is a copy of the "h" structure at the time that set() is executed -- a copy in which the counter is 0. When you increment h.counter inside increment(), a copy of that structure is made, and you increment that copy. So there is the captured structure with counter 0, and there is the copied structure that then had its counter incremented to 1. And then since that h that had the increment is in the local workspace of increment(), that incremented h is discarded. When the callback is next called, it is the captured (0 counter) structure that is used...
Please see the FAQ about sharing variables, http://matlab.wikia.com/wiki/FAQ
[Added example]
The below makes use of nested functions with shared variables.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Matlab GUI without Guide % 05/15/2012
function simpleGui
h.counter = 0;
h.fig = figure('position',[1000,500,210,60]);
h.button = uicontrol('style','pushbutton',...
'position',[10,10,100,40],...
'string','button');
set(h.button,'callback',@increment);
function increment(hObject,eventdata)
h.counter = h.counter + 1;
set(h.button,'string',num2str(h.counter));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%