MATLAB: Attempted to access colors(6); index out of bounds because numel(colors)=5

errorindexMATLABout of bounds

Hi, I tried executing this loop,
colors = ['m';'y';'b';'g';'c'];
loop_ind = 1;
for k1 = 1:5
figure(4);
linespec = colors(loop_ind);
plot(x, y, linespec, 'LineWidth', 1);
loop_ind = loop_ind + 1;
hold on
end
legend('-0.02','-0.01','0','0.01','0.02')
But I get an error,
Attempted to access colors(6); index out of bounds because numel(colors)=5. Error in test_contact_ellipse (line 228)
linespec = colors(loop_ind);
Now I'm getting the plot with the correct colors but the legend doesn't appear. How can I rectify this error.
Please give your suggestions.
Thanks

Best Answer

  • This is an example that plots in different colors with a matching legend:
    c = [0 1 0; 1 0 0; 0 0 1; 1 0 1; 0 1 1];
    x = linspace(0,2*pi);
    figure(4)
    hold on
    for k1 = 1:size(c,1)
    plot(x, sin(x*k1)+k1, 'Color', c(k1,:))
    end
    hold off
    grid
    legend('Color 1', 'Color 2', 'Color 3', 'Color 4', 'Color 5')
    Adapt it as necessary to your application.