user7670190
user7670190

Reputation: 15

Vectors must be the same lengths error in matlab

I want to plot f(x)=5xcos(x)-x and it's first derivative in same plot for -2pi<= x <=2pi using MATLAB. But I get the folowing error:

Error using ==> plot Vectors must be the same lengths."

y1 = 5.*x.*cos(x)-x;
y2 = diff(y1);
plot(x,y1,'-',x,y2,'-*')

what should I do?

Upvotes: 0

Views: 599

Answers (1)

Suever
Suever

Reputation: 65430

diff takes the pairwise difference between successive elements and is therefore 1-element shorter than the input vector. As a result, if you want to plot it, you'll want to either append (or prepend) a 0 or just plot with one less x

plot(x, y1, '-', x, [0, y2], '-*')

% OR
plot(x, y1, '-', x(1:end-1), y2, '-*')

Upvotes: 1

Related Questions