I have a figure in MATLAB with some lines, that get automatically assigned to various colors, and I want to set the same color sequence to other figure objects.
For example:
x = 0:10; y = 0:0.5:5;
h = plot(x,y+1, x,y+2), hold on
g = plot(x,y-1, x,y-2)
% want to get the bottom two lines to match respectively the colors of the top two lines
% suggested code:
g.Color = h.Color; % doesn't work
I know that I can use the following code to set the colors of multiple line objects simultaneously, but I've only managed to figure out how to use it to set all the line objects to a single color. (Instead, I would like each line object in 'g' to take a different color value, ie the color of its corresponding index line object from 'h').
set(g,'Color', [1 0 0]);
I would like to avoid looping through and setting each line individually, like
g(1).Color = h(1).Color; % ...
I've tried various ways of wrapping or casting the output of g and g.Color and h.Color like [g.Color], g(:).Color, g{:}.Color, etc, but I have not managed to find something to work. I also tried using cellfun(@(x,y) x.Color = y.Color, g, h) and similar codes, but with no success. I am actually not entirely clear on the data structure of these objects-- seems to me that g.Color lists out values like a cell array does, but that it is not actually a cell array..
Again the goal is to set the color of multiple line objects in a graphics handle each to different colors, in a single line of code, and specifically to the colors from another graphics handle object (that has the same number of line objects).
Thanks for any advice!
Your g
and h
are both arrays of Line
objects. While you can use the simplified syntax h.Color
to access the Color
property of all objects at once, what you get is not a single result, but a sequence of results:
>> g.Color
ans =
0.929 0.694 0.125
ans =
0.494 0.184 0.556
To assign several values to several variables in one =
expression, use the syntax
[g.Color] = h.Color;
See "Example 3" in the documentation of deal
.