2

Is there a way to vectorize/accelerate the task of plotting multiple lines with different colors?

The working-but-slow approach is

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

I tried

X = [1 2; 3 4];
Y = [2 -4; 5 2];
figure;
plot(X, Y, 'Color', [1 0 0; 0 1 0]);

but no luck.

Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174
  • 1
    Can't test right now but maybe you can try setting axis limits manually once before plotting so that Matlab does not need to figure every time if it needs to re-calculate them; check [this](http://undocumentedmatlab.com/blog/plot-performance) article by Yahir Altman and a few tips in the commentary below the text. Hope that helps somehow! – Benoit_11 Oct 23 '16 at 02:09
  • 1
    Have a look here: http://stackoverflow.com/a/22029354/2778484 – chappjc Oct 23 '16 at 02:09
  • One known improvement: use low-level function `line` over `plot`. – Sibbs Gambling Oct 23 '16 at 02:41
  • Hey @chappjc, you should come here more often :-P – Luis Mendo Oct 23 '16 at 03:22

1 Answers1

2

This is probably too hacky to be a useful replacement of the loop, but here it goes:

set(gca, 'ColorOrder', [1 0 0; 0 1 0], 'NextPlot', 'add')
plot(X, Y);

The 'ColorOrder' property contains the colors to be used by default for new plots. Setting 'NextPlot' to 'add' seems to be necessary so that the call to plot doesn't reset 'ColorOrder' to its default value.

Tested on R2015b.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • +1; thanks! Wondering if this would really make things faster? My ultimate goal is to accelerate things (not just vectorizing) :-D – Sibbs Gambling Oct 23 '16 at 03:28
  • 1
    @SibbsGambling Not sure about speed, better try in your Matlab version and specific case. But the loop is much more readable; I'd probably go with that – Luis Mendo Oct 23 '16 at 03:36
  • Oh but what if my colors are RGBA instead of RGB? Just tried -- `set(gca, 'ColorOrder', colors);` doesn't really take in four columns. – Sibbs Gambling Oct 31 '16 at 01:01
  • 1
    @SibbsGambling Matlab doesn't support alpha as part of the color specifcation, as fas as I know. You can specify the alpha of a graphic object separately. But that doesn't work for `plot`; only for `surface` etc. So you probably need to do the alpha computation by hand to convert to RGB colors – Luis Mendo Oct 31 '16 at 09:41