Callback Functions

Learn about the callback, which is a function that is triggered when a defined action is performed on a specified GUI element.

A callback function is passed as an argument of uicontrol, which is then invoked to complete a user-defined routine or action.

The following example walks you through the steps to create a pushbutton that plots a sine curve when pressed.

  1. Assign a uicontrol function to a new variable that is the button_handle.
  2. Define the handle of the uipanel as the parent object’s handle.
  3. Determine the units used as normalized.
  4. Assign the position as [0.02 0.05 0.2 0.05] in normalized units.
  5. Define the style of the control object as pushbutton.
  6. Define the name of the pushbutton with the help of the string option as Plot.
  7. Assign the callback function as @plot_curve.
  8. Define the callback function that plots a sine curve and takes two arguments.
clear all; close all; clc;
global panel1;
function plot_function(handles,callback)
     global slider_handle;
     freq_value = 1;
     t = [0:1/128:1];
     x = sin(2*pi*freq_value*t);
     plot(t,x);
end
f = figure('units','normalized','position',[0 0 0.9 0.9]);
panel1 = uipanel(f,'units','normalized','position',[0 0.1 0.99 0.89]);
axes('units', 'normalized', 'position', [0.2 0.15 0.7 0.7]);
button_handle = uicontrol(panel1,'style','pushbutton','units','normalized', ...
            'position',[0.02 0.1 0.17 0.05],'string','Plot',...
            'callback',@plot_function);

The code example produces a GUI that displays the following sin curve when the Plot button is clicked: