I'm trying to calculate the first derivative of a function at a number of points using the 4-th order finite difference matrix, and then multiplying it with the function values at that point. I wrote this module (for arbitrary order of derivative), then defined an example grid and function to test it: der4[gridpoints_,values_,order_]:= Module[{x=gridpoints, y=values, k=order}, de=NDSolve`FiniteDifferenceDerivative[Derivative[k],N[x],"DifferenceOrder"->4]@"DifferentiationMatrix"//Normal//MatrixForm; de.N[y]]

number=31; f[x_]:=Exp[-8*x^2]; grid=Subdivide[-1, 1, number]; val=f[grid]; der4[grid,val,1]

I get a matrix that at least looks like what it needs to, but also the following error:

SetDelayed::write: Tag Plus in (-2 dx+dx (-1+x)+x3)[x_] is Protected.

and this string (-2 dx+dx (-1+x)+x3)[x_] appears between the multiplication of the matrix and the values vector, can anyone help with this?

  • $\begingroup$ @DanielHuber I did it and I get the same error. Besides, de4 needs to be a matrix, so that it can be properly multiplied with the values from the left. $\endgroup$
    – JBuck
    Nov 17, 2021 at 20:04
  • 1
    $\begingroup$ Unable to reproduce after removing MatrixForm. Try with a fresh kernel. $\endgroup$ Nov 17, 2021 at 20:15
  • 1
    $\begingroup$ Sorry, I meant Matrix not Vector: If you write: de= ... //MatrixForm then you get MatrixForm[...] and not a list of list of lists (matrix). Therefore delete the MatrixForm. $\endgroup$ Nov 17, 2021 at 20:29
  • $\begingroup$ I deleted MatrixForm and used kernel (I was running everything as a Script), and it seems to work, thank you both! Curiously enough, I ran another script that was running perfectly fine yesterday, and the same error popped up randomly, making one of my plots disappear, any clue why this happens? So that I know what to avoid in the future $\endgroup$
    – JBuck
    Nov 17, 2021 at 20:37


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.