less than 1 minute read

Published:

To change different path using keyboad in Matlab gui.

Steps

  • A custom callback function file, *.m file
  • set the ‘KeyPressFcn’ function to the matlab figure

Step 1: Custom callback function file format

I create my custom ‘key_pressed_fcn’ function with 4 inputs as following.

function key_pressed_fcn(fig_obj,eventDat,polys,h)
% Input:
%     p - layer points data (include mutil polys split by NaN)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 
global id_poly
% get(fig_obj, 'CurrentKey')
% get(fig_obj, 'CurrentCharacter')
% get(fig_obj, 'CurrentModifier')
cla(h)
n = length(polys);
switch eventDat.Key
    case 'leftarrow'
        disp('Pressed leftarrow')
        id_poly = mod(id_poly-1,n);
    case 'rightarrow'
        disp('Pressed rightarrow')
        id_poly = mod(id_poly+1,n);
end
axis([-80 80 -100 100]);
plot_OnePoly(polys{id_poly});

Step 2: Set the ‘KeyPressFcn’ function to the figure handle

  • the figure handle is ‘gcf’ usually
    set(gcf,'KeyPressFcn',{@key_pressed_fcn, polys,h});
    

Instead of using global variable here, I prefer to transmit the need data to callback function. But you can also use global vars if you do want.