MATLAB: “For loop” not allowed in commandscript called inside nested function

attempt to add to a static workspacecommand scriptnested functionprogrammed gui

I have a basic question: I want to display 5 asterisks in the workspace (using a for loop) every time the button is pressed. I was using a command script inside my nested function. But MALTAB gave me the following error:
??? Attempt to add "k" to a static workspace. See MATLAB Programming, Restrictions on Assigning to Variables for details.
Below is my very simple code.
(1) File 1: my simpleGUI.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%



% simpleGUI.m file
% 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) % nested function
% command script for incrementing h.counter and displaying 5 asterisks
increment_counter;
set(h.button,'string',num2str(h.counter));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
(2) File 2: my command script file, increment_counter.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% command script file: increment_counter.m
% 05/25/2012
h.counter = h.counter + 1;
for k = 1:1:5
disp('*');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
If I comment out the for loop for asterisk display, the command script runs ok inside the nested function. But why is the for loop not allowed? Any ideas?
Thanks in advance!
Yunde

Best Answer

Did you look into the link with the error message:
Specifically: MATLAB issues an error if you attempt to dynamically add a variable to the workspace of an anonymous function, a nested function, or a function that contains a nested function. Examples of operations that might use dynamic assignment in this way are shown in the table below.
Assigning to a variable in a MATLAB script Convert the script to a function, where argument- and result-passing can often clarify the code as well.