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

1 回表示 (過去 30 日間)
Priya
Priya 2014 年 6 月 24 日
コメント済み: Star Strider 2014 年 6 月 26 日
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
  5 件のコメント
Sara
Sara 2014 年 6 月 24 日
Attach x and y, with random data it works fine. Are x and y multidimensional arrays by any chance?
Sara
Sara 2014 年 6 月 24 日
You'll need to include all the variables and the files, or I won't be able to run your code

サインインしてコメントする。

採用された回答

Star Strider
Star Strider 2014 年 6 月 24 日
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.
  9 件のコメント
Priya
Priya 2014 年 6 月 26 日
Thanks again. It worked.
Star Strider
Star Strider 2014 年 6 月 26 日
Again, my pleasure!

サインインしてコメントする。

その他の回答 (1 件)

Sara
Sara 2014 年 6 月 24 日
In the last loop, replace with the following and see if it is what you are looking for:
figure(4);
plot(x, y, 'LineWidth', 1,'color',colors(k2))
axis square;
axis equal;
grid on;
xlabel('Longitudinal');ylabel('Lateral');title('Contact ellipse shape');
hold on
myh = line([xCenter, xCenter], [yCenter - yRadius(k2), yCenter + yRadius(k2)], ...
'LineWidth', 1, 'Color', [1,0,0]);
set(get(get(myh,'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
myh = line([xCenter - xRadius(k2), xCenter + xRadius(k2)], [yCenter, yCenter], ...
'LineWidth', 1, 'Color', [1,0,0]);
set(get(get(myh,'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
It seems that some of your ellipses are overwritten with others. Since I don't know what you are doing, this is the best I can recommend. I'd replace also:
for k2 = 1:size(a,2)
  1 件のコメント
Priya
Priya 2014 年 6 月 25 日
Sara, thanks for your help, it's working now.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by