Colors in the legend do not match the plot

I need to build several Maclaurin series and I am having legend issues.

For these two equations -

x = (-1:.01:1);

% e^x
eqtn21 = 1; 
eqtn22 = 1 + x;
eqtn23 = 1 + x + x.^2/2;
eqtn24 = 1 + x + x.^2/2 + x.^3/6;
eqtn25 = exp(x);

% cos(x)
eqtn31 = 1;
eqtn32 = 1 - x.^2/2;
eqtn33 = 1 - x.^2/2 + x.^4/24;
eqtn34 = 1 - x.^2/2 + x.^4/24 - x.^6/720;
eqtn35 = cos(x);

subplot(2,2,1)
    plot(x,eqtn21,'r',x,eqtn22,'g',x,eqtn23,'b',x,eqtn24,'k',x,eqtn25,'c')
    legend('First Term','First Two Terms','First Three Terms','First Four Terms','Exact Function')

subplot(2,2,2)
    plot(x,eqtn31,'r',x,eqtn32,'g',x,eqtn33,'b',x,eqtn34,'k',x,eqtn35,'c')
    legend('First Term','First Two Terms','First Three Terms','First Four Terms','Exact Function')

      

When I draw them, the legend appears but shows 5 red lines and doesn't match the colors in the graph.

+3


source to share


1 answer


The problem is related to eqtn21

and eqtn31

. They have a size of 1, and x

a vector of a different size. When you draw, you need to match their dimensions to size x

if you want to have a constant string (so for all x values, you get 1) oreqtn21 = [1 1 1 1 ... 1];

An easy way to do this is to write eqtn21 = 1+0*x;

, etc. Other ways to do this can be modified eqtn21

with repmat

or by matrix multiplication, etc ...

eqtn21=repmat(1,[1 numel(x)])

      



or

eqtn21=1*ones(1,numel(x))

      

etc...

+1


source







All Articles