Search code examples
matlabderivative

Matlab - second derivative of data


Let's say we have

[x]=[0.1 0.2 0.3 0.4]
[y]=[0.25 0.30 0.40 0.55]
y1=diff(y)./diff(x)
y2=diff(y1)./diff(x)

And the result I get is

Matrix dimensions must agree

How do I solve this problem?


Solution

  • I redirect you towards this documentation. When you use the diff function, it will actually return you a vector with m-1 (m being its length), since what it does is output this:

    diff(y1) = [y1(2)-y1(1) y1(3)-y1(2) ... y1(m)-y(m-1)]
    

    As you can see, you will loose one value, and thus explaining your error. When you do your last line, it cannot divide diff(y1) by diff(x) since diff(y1) is equal to a vector of length 2 and diff(x) is equal to a vector of length 3.

    Depending on what you want to do, you can change the code to the following :

    [x]=[0.1 0.2 0.3 0.4]
    [y]=[0.25 0.30 0.40 0.55]
    y1=diff(y)./diff(x)
    y2=diff(y1)./diff(x(1:end-1))
    

    If you want to approximate the derivate of y, I really suggest you to take a look at the example in the page I linked. The matlab documentation always gives examples on how to use their functions, so go take a look. According to the documentation, if you want to calculate the partial derivate of the vector y, you need the step of your x vector.

    x=[0.1 0.2 0.3 0.4]
    y=[0.25 0.30 0.40 0.55]
    x_step = 0.1
    y1=diff(y)./x_step
    y2=diff(y1)./x_step