MATLAB: How to determine which subplot number I am clicking on

axesaxisclickMATLABnumbersubplot

I have multiple subplots in a figure. I want to be able to click on a subplot and know which subplot I am clicking on. Then I want to access the handle to that axis and the one adjacent to it.
For example:
I have a 3×2 matrix of subplots. When I click on any subplot, I want the whole row to have the axes turn green.
for i=1:6
subplot(3,2,i)
plot(1:i*3)
legend(num2str(i))
end

Best Answer

This can be done by accessing the current axes ("gca") and then comparing it to all the other axes that are children of the figure until a match is found. This will give the number of the axes in the matrix.
Note: the axes are counted in reverse order by columns so for our 3x2 matrix the axes are counted as:
[6 5
4 3
2 1]
Use the "findobj" function to find all the axes in the figure and then use the "find" function to see which one matches the currently clicked axes:
f=gcf;
axesClicked = gca;
allAxes = findobj(f.Children,'Type','axes');
numClicked = find(axesClicked==allAxes);
Once you know which axis number it is, you can find the neighboring axes with a simple if statement:
if mod(numClicked,2)
numAdjacent = numClicked+1
else
numAdjacent = numClicked-1
end
Then simply use the number to index into "allAxes" and change the background color to green:
axesAdjacent = allAxes(numAdjacent);
axesClicked.Color = 'g';
axesAdjacent.Color = 'g';