Search code examples
matlabmatlab-figure

MATLAB copyobj reverses the order of objects?


I was debugging a large graphics project and finally reduced the problem into the following MWE. Somehow MATLAB's copyobj reverses the order of the graphics objects when it copies them to a new figure.

X = [1 2; 4 4];
Y = [2 -4; -4 2];
figure;
hold on;
colors = [1 0 0; 0 1 0];
lines  = [];
for idx = 1:size(X, 2)
    l = plot(X(:, idx), Y(:, idx), 'Color', colors(idx, :), 'linewidth', 10);
    lines = [lines l];
end
hold off;

gives

enter image description here

As expected, the green line that was drawn later is on top of the red line. Then I copy these two lines into a new figure.

figure;
a = axes;
copyobj(lines, a);
view(a);

gives

enter image description here

Now the red is above the green.

Does anybody know the reason behind this? To get the order correct, can I just reverse the object order?


Solution

  • copyobj copies the objects in the reverse order.
    To get the correct order, use copyobj(lines(end:-1:1), a); or copyobj(fliplr(lines), a); instead of copyobj(lines, a);


    An advice on your code:-
    Instead of growing the size of lines on every iteration, pre-allocate it as shown below:

    lines = gobjects(1,2);
    for idx = 1:size(X, 2)
        lines(idx) = plot(X(:, idx), Y(:, idx), 'Color', colors(idx, :), 'linewidth', 10);
    end
    

    Read the documentation of gobjects() and Graphics Arrays for details.

    And if using the loop is not a requirement for you, you can simply use the following:

    % Following is to set the Colors that you specified
    set(gca, 'ColorOrder', colors);
    % Now plotting the data 
    lines = plot(X,Y,'linewidth',10 );