# Using a for loop for legend plots

1 view (last 30 days)
Bob on 15 Dec 2014
Answered: Amit on 15 Dec 2014
I was able to make each point a different color in my plot. I want to do the same thing for the legend. How can I put the legend for each data point using a for loop?
Here is my code.
Z=[3 1 7];
for i=1:length(Z)
A(i)=Z(i)+2;
B(i)=Z(i)-7;
C(i)=Z(i)+4;
col=['g' 'b' 'r'];
for j:length(col)
x=[1 2 3];
y(:,i)=[A(i) B(i),C(i)];
subplot(3,1,i)
plot(x,y(:,i),'color',col(i))
end end
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Accepted Answer

Amit on 15 Dec 2014
Z=[3 1 7];
for i=1:length(Z)
A(i)=Z(i)+2;
B(i)=Z(i)-7;
C(i)=Z(i)+4;
col=['g' 'b' 'r'];
legendtext = ['a' 'b' 'c']; %%Add your legend text
for j=1:length(col)
x=[1 2 3];
y(:,i)=[A(i) B(i),C(i)];
subplot(3,1,i);
plot(x,y(:,i),'color',col(i))
legend(legendtext(i));
end
end
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Categories

Find more on Legend in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!