MATLAB: Unexpected behavior in “legend” while plotting

MATLAB

The "legend" function appears to show unexpected behavior when plotting. Consider the following code snippet:
>> a=1:10;
>> b=2*(1:10)
>> c=3;
>> p1=plot(a,c,'ro');hold on;
>> p2=plot(a,b);
>> legend('a','b')
The above code generates the following figure:

In the above plot the legends seem to be incorrect. I would expect the legend 'b' to correspond to the line and not the marker

Best Answer

This is an expected behavior of "plot" and not a bug with "legend". This is because you can observe "p1" to be a 10x1 line object on executing the above code, ie a separate line object is created for each of the 10 points in "a". This is because the variable plotted "c" is a 1x1 double element and not a vector. If you would like to plot the value stored in "c" as the y-value for each x-value in "a", you can multiply "c" by a vector of 1's, and a single line object containing the 10 points will be generated:
>> p1=plot(a,c*ones(1,10),'ro');hold on;