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:
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';
Best Answer