priyanka
priyanka

Reputation: 25

Erratic behavior of Matlab's legend function

I was working on a MATLAB project and found some strange behavior of the legend function. Here is the code to reproduce the issue:

X=rand(3,100);
a=rand(3,100);
b=rand(3,100);
figure(1); hold on;
plot(0.17663,'m');
plot(1.223,'y');
plot(X,a,'r');
plot(X,b,'g');
legend({'s1','s2','a','b'});

My question is: The legend in the picture shows the same color for plot 3 and plot 4. Instead it should show red and green respectively. Is there something wrong with legend?

https://i.sstatic.net/j6JbH.png

Upvotes: 0

Views: 54

Answers (1)

knedlsepp
knedlsepp

Reputation: 6084

The commands plot(X,a,'r') and plot(X,b,'g') are not what you might expect. As X is a 3-by-100 array they will plot 100 lines, each consisting of 3 points, start, middle, end. The legend entries will correspond to each single line, so you should expect 100 red legend entries. You will see different behavior if you pass transposed arrays: plot(X.',a.','r'). This will plot 3 lines, each consisting of 100 points.

Upvotes: 1

Related Questions