How do you change a variable in the workspace with a push button?
Show older comments
When a certain if statement is true, I want to get two push buttons. Then the user can choose 'left' or 'right'. When he choose 'left', the variable I must become I+1. When he choose 'right', the variable I must become I-1.
I can get the buttons (in a different script) but I cannot change the variable I. My code is:
function Doesnotfit
h.fig=figure('position',[1100 30 210 60])
h.buttonleft= uicontrol('Style', 'pushbutton', 'String', 'Go left','Position', [0.1 0.1 50 20]);
set(h.buttonleft,'callback', {@Ileft,h})
h.buttonright= uicontrol('Style', 'pushbutton', 'String', 'Go right','Position', [100 0.1 50 20]);
set(h.buttonright,'callback', {@Iright,h})
end
function h=Ileft(hObject,eventdata,h)
evalin('base','I')
I=I-1
end
function h=Iright(hObject,eventdata,h)
evalin('base','I')
I=I+1
end
Thanks in advance!
3 Comments
@Rick van den Hadelkamp: solving this with evalin or assignin will make code that is slow, buggy, hard to debug, and hard to follow:
It is much simpler, faster,, more reliable, and easier to use nested functions:
Also note that callback functions do not return any arguments, so that h= does not do anything.
Rick van den Hadelkamp
on 24 Jul 2017
@Rick van den Hadelkamp: simply search this forum for the hundreds of other threads that explain this, with examples:
etc, etc
Answers (1)
Nested functions are simpler and faster (untested):
function doesnotfit
%
I = 0;
fgh = figure('position',[1100,30,210,60]);
%
uicontrol('Parent',fgh, 'Style', 'Pushbutton', 'String', 'Go left',...
'Position',[0.1,0.1,50,20], 'Callback', @Ileft);
uicontrol('Parent',fgh, 'Style', 'Pushbutton', 'String', 'Go right',...
'Position',[100,0.1,50,20], 'Callback', @Iright);
%
function Ileft(~,~)
I=I-1
end
%
function Iright(~,~)
I=I+1
end
%
end
2 Comments
Marco Boesso
on 27 Nov 2020
Hey dude, I hope you will read this, because I'm in trouble and I need to perform a situation like this one.
I tried to copy and paste your code, so thank you in advance. But when I push the buttons I get this error:
Unrecognized function or variable 'I'.
Error in Sandbox>Ileft (line 14)
I=I-1
Error while evaluating UIControl Callback.
function Ileft(~,~)
I=I-1
end
Line 14 is "I=I-1" in my very small script to try your stuff out. The same issue happens if I click the right button.
I've got MATLAB R2020b, academic use.
Stephen23
on 27 Nov 2020
"I tried to copy and paste your code, so thank you in advance. But when I push the buttons I get this error"
I copied and pasted the entire code and ran it. No error in either R2012b or R2015b:

Most likely you made some changes to the code, such as converting the nested functions to ordinary local functions.
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!