Consider the following MATLAB code that sets a callback for a button press. What will be printed when the button is pressed?
function testCallback btn = uicontrol('Style','pushbutton','String','Click me', ... 'Position',[100 100 100 40], 'Callback', @buttonPressed); function buttonPressed(src, event) disp('Button was clicked!') end end
Look at what the callback function buttonPressed does when the button is clicked.
The callback function buttonPressed is called when the button is clicked, and it prints 'Button was clicked!'.
Choose the correct statement about callback functions in MATLAB GUI programming.
Think about the different ways MATLAB allows you to specify callbacks.
MATLAB supports callbacks as function handles to nested functions, anonymous functions, or separate functions. They can accept inputs and execute only when triggered.
Examine the code below. When the button is clicked, it causes an error. What is the cause?
function faultyCallback btn = uicontrol('Style','pushbutton','String','Click', ... 'Position',[100 100 100 40], 'Callback', @buttonPressed); end function buttonPressed(src, event) disp('Clicked!') end
Consider MATLAB's function visibility rules for callbacks.
Since buttonPressed is a separate function in the same file but not nested, MATLAB cannot find it as a callback unless the file is saved separately or the function is nested.
You want to assign a callback to a button that calls myCallback with extra arguments arg1 and arg2. Which option is correct?
Think about how to use anonymous functions to pass extra arguments in callbacks.
Using an anonymous function with the correct input arguments src and event allows passing extra arguments to myCallback.
count after this callback sequence?Consider this MATLAB GUI code that counts button clicks using a persistent variable inside the callback. What is the value of count after pressing the button 3 times?
function clickCounter btn = uicontrol('Style','pushbutton','String','Count clicks', ... 'Position',[100 100 120 40], 'Callback', @countClicks); function countClicks(~,~) persistent count if isempty(count) count = 0; end count = count + 1; disp(['Clicked ' num2str(count) ' times']); end end
Remember how persistent variables keep their value between function calls.
The persistent variable count starts at 0 and increments by 1 each time the callback runs, so after 3 clicks it is 3.
