MATLAB Matlab Second Derivative Ploting Problem

AI Thread Summary
The discussion revolves around a user seeking assistance with a Matlab program designed to calculate and plot the second derivative of a polynomial function. The user encounters an error stating that the vectors must be of the same length when attempting to plot the function and its derivatives. It is clarified that the "diff" function reduces the length of the array, resulting in fewer components for the derivatives. To resolve the issue, it is suggested that the user should interpolate the last component of the derivative arrays to match the original array's length. The user acknowledges the advice and expresses a willingness to try the suggested interpolation method.
el_pohl
Messages
3
Reaction score
0
Hello, this is my first post in this site, so here goes:

Im working on a Matlab program. I have to calculate the second derivative of a given equation. The problem is that plotting the derivative is necessary, and that's where I'm stuck.

Here's what I've got so far:

% Evaluar f(x) y f'(x) usando diferencias hacia atras.
%
x = -10:0.1:10;
f = x.^3 - 5*x.^2 + 2*x + 8;
df = diff(f);
dx = diff(x);
df_dx = df./dx;
xd = x(2:length(x));
d2f = diff(f,2);
d2x = diff(f,2);
d2f_d2x = d2f./d2x;
%
% Graficar lo anterior.
%
subplot(2,1,1),...
plot(x,f,xd,df_dx,xd,d2f_d2x),...
title('Derivada de un polinomio de quinto grado'),...
xlabel('x'),grid,...
ylabel('f(x)'),...
axis([-4,5,-500,1500]);

On the internet I found out that diff(f,2) would calculate the second diff, I guess that's true. Ignore the spanish text :P.

When I try to run the program, the following appears:

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

Error in ==> C:\MATLAB6p5\work\segunda_diferencial.m
On line 16 ==> plot(x,f,xd,df_dx,xd,d2f_d2x),...

Hope you can help.

Thanks!
 
Physics news on Phys.org
De donde eres? Casi no se nota que hablas español.


Well, the command line "diff" shortens one dimension the array:

diff (\overline{x})=[x_2-x_1, x_3-x_2,...x_n-x_{n-1}]

you will obtain a n-1 array dimension.

You should interpolate the last component from interior ones, in order to have n components.

With diff2 is the same, surely you will obtain n-2 components.
 
Gracias! Soy del norte de México.

In fact, I can graph the first diff, though what you say does make sense, as with every consecutive derivative one constant term will dissappear.

Interpolate? As with 'interp1'? The last component? d2f_d2x in my code?

Casi no se nada de Matlab :(

Thanks for that, I will try it out, hope I understood you...
 
Ok, I got it! Thanks though.
 

Similar threads

Back
Top