MATLAB: Using uicontrol in a figure

axesgridMATLABuicontrol

I have a script that I use to plot track data that has three subplots within a figure. I want to use uicontrol to create a toggle button that has a callback to the matlab function grid so that I can toggle the grid on and off. The problem is that I can only toggle the grid in the last subplot but it doesn't work for the first two. Here's most of my plotting script:
%%Set up axes
figure('numbertitle','off')
set(gcf,'Name',filename);
h1 = gcf;
axis off
%%X Plots
subplot(2,2,1)
ax = gca;
%x_axis = get(ax);
xlim([t(1) t(end)])
ylim([-10 30])
ylabel('x [m]')
grid on
hold on
%%Y Plots
subplot(2,2,3)
ay = gca;
%y_axis = get(ay);
h3 = plot([t(1) t(end)],[-half_lane -half_lane],'--',...
[t(1) t(end)],[half_lane half_lane],'--');
set(h3,'Color',[0.5 0 0])
ylabel('y [m]'), xlabel('time [sec]')
xlim([t(1) t(end)])
ylim([-10 10])
grid on
hold on
%%X-Y Plot
subplot(2,2,[2 4])
axy = gca; % get the axis information
xy_axis = get(axy);
car_y = [0 -5.182] + xy_axis.YLim(1);
load 'car.mat'; image([-0.9350 0.9350], car_y, car); clear car; % plot the car for reference
set(gca,'YDir','normal','XDir','reverse'), hold on
xlim([-10 10]);
ylim([-10 25]);
xlabel('y [m]'), ylabel('x [m]')
title(filename,'interpreter','none')
grid on
axis equal
arc_plot([-sensor(1).orientation(2) sensor(1).orientation(1)], (270-sensor(1).orientation(3)), C(1,:));
arc_plot([-sensor(2).orientation(2) sensor(2).orientation(1)], (90-sensor(2).orientation(3)), C(2,:));
arc_plot([-sensor(3).orientation(2) sensor(3).orientation(1)], (90-sensor(3).orientation(3)), C(3,:));
arc_plot([-sensor(4).orientation(2) sensor(4).orientation(1)], -(90+sensor(4).orientation(3)), C(4,:));
xy_axis = get(axy);
%%plot lane
h = plot([-half_lane -half_lane],xy_axis.YLim,'--',[half_lane half_lane],xy_axis.YLim,'--');
set(h,'Color',[0.5 0 0])
%%link axes and insert grid toggle
linkaxes([ax ay],'x');
uicontrol(h1,'Style', 'togglebutton', 'String', 'Grid',...
'Position', [20 20 50 20],...
'Callback', 'grid');

Best Answer

  • Hi Ryan,
    You will need to call grid for each of the subplots in your figure. To do that, cache the return values for each of the calls to subplot, and then make one call to grid for each of the subplots, passing each of the cached handles in turn.
    I'm not sure whether your code is executing in a script or as part of a larger program, so you might be able to just write the three calls inline in your uicontrol call (i.e. ('Callback', 'grid(ax1);grid(ax2),grid(ax3)')) or you may need to put these calls in another function.
    I hope this helps,
    -Brian