MATLAB: How to use up and down arrow keys to scroll through the plots in MATLAB 7.7 (R2008b)

examplefunctionkeyMATLABpress

I would like my users to be able to scroll through different plots using up and down arrow keys. I tried using the PAUSE command, but this does not let users scroll in two directions (both forward and backward) through the plots.

Best Answer

If you create plots on different axes and then put all axes in the same figure window, you can use the WindowKeyPressFcn to scroll forward and backwards through the plots. Set the axes visibility to 'off' for all but the plot you are trying to display, and then, in the WindowKeyPressFcn callback, use the up or down arrow key to change the visibility to the next or previous plot.
The following code demonstrates an example. To run it, place the code in a file named "scrolldemo.m" on your MATLAB path. Then type "scrolldemo" at the MATLAB command prompt. When you use up and down arrow keys on the figure that appears, you will scroll through different plots.
function scrolldemo
plot(1:10)
ax1 = gca;
ax2 = axes('position',get(ax1,'position'));
plot(ax2,10:-1:1)
ax3 = axes('position',get(ax1,'position'));
plot(ax3,1:10,repmat(5,1,10));
f = gcf;
set(findobj(ax2),'Visible','off');
set(findobj(ax3),'Visible','off');
set(f,'WindowKeyPressFcn',@scrollaxes)
function scrollaxes(src,evt)
allax = findobj(src,'Type','Axes');
currax = findobj(src,'Type','Axes','Visible','on');
nextdownkey = allax([2:end 1]);
nextupkey = allax([end 1:end-1]);
if strcmp(evt.Key,'downarrow')
set(findobj(currax),'Visible','off')
set(findobj(nextdownkey(currax==allax)),'Visible','on');
elseif strcmp(evt.Key,'uparrow')
set(findobj(currax),'Visible','off')
set(findobj(nextupkey(currax==allax)),'Visible','on');
end