Question

I would like to create a figure, and once subplots have been created, I would like to apply properties to all of them simultaneously, without going through a for-loop. In fact, I would like to do all the following without having the need to go through a for-loop:

  • Create all subplots without a for-loop. (For example, create a figure with 4x5 subplots, not using a for-loop).
  • Apply the same background color to each subplot w/o a foor-loop.
  • Apply the same axis command to all of them w/o a for-loop. (Like axis equal, axis tight, etc).

Is there a way to do this?

Was it helpful?

Solution

The most convenient approach is to create an array of axes handles, and then to set properties:

for i=1:4,
   axesHandles(i) = subplot(2,2,i);
   plot(...)
end

%# set background to black for all handles in the array
%# note that this needs no loop
set(axesHandles,'color','k')

If you don't have the axes handles collected, you need to collect the array of handles first. For this, you can use the children properties of the figure window (gcf gets the handle of the currently active figure)

axesHandles = get(gcf,'children');

and if you have axes across several figures, you can use findall to collect everything:

axesHandles = findall(0,'type','axes');

From then on, it's again a single call to set, or to axis, for example

set(axesHandles,'color','k','lineWidth',2)
axis(axesHandles,'tight')

OTHER TIPS

I can't understand why you think that for loop is evil, but anyhow ...

Here is an answer on part 2 and 3 of your question, assuming that the axes handles were saved in an array:

   a(1) = axes();
   a(2) = axes();
   arrayfun( @(x)(set(x,'Color','r')),a);
   arrayfun( @(x)(axis(x,'equal')),a);

arrayfun applies a function to each and one of the elements in a. Anonymous function in this case is only a shortcut for writing it in the following way:

   a(1) = axes();
   a(2) = axes();
   arrayfun( @SetRedColor ,a);
   arrayfun( @SetAxisEqual,a);

   function SetRedColor(x)
       set(x,'Color','r');
   end

   function SetAxisEqual(x)
       axis(x,'equal');
   end

Another possible way is to link the axes, and set only one property:

   linkprop(a,'Color');
   set(a(1),'Color','r'); %#Now a(2) color is also red
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top