Dave S
Dave S

Reputation: 136

Numerical integration of symbolic differentiation - MATLAB

The following is a MATLAB problem.

Suppose I define an function f(x,y). I want to calculate the partial derivative of f with respect to y, evaluated at a specific value of y, e.g., y=6. Finally, I want to integrate this new function (which is only a function of x) over a range of x.

As an example, this is what I have tried

syms x y; f = @(x, y) x.*y.^2; Df = subs(diff(f,y),y,2); Int = integral(Df , 0 , 1),

but I get the following error.

Error using integral (line 82) First input argument must be a function handle.

Can anyone help me in writing this code?

Upvotes: 1

Views: 1116

Answers (2)

horchler
horchler

Reputation: 18504

Keeping it all symbolic, using sym/int:

syms x y;
f = @(x, y) x.*y.^2;
Df = diff(f,y);
s = int(Df,x,0,1)

which returns y. You can substitute 2 in for y here or earlier as you did in your question. Not that this will give you an exact answer in this case with no floating-point error, as opposed to integral which calculated the integral numerically.

When Googling for functions in Matlab, make sure to pay attention what toolbox they are in and what classes (datatypes) they support for their arguments. In some cases there are overloaded versions with the same name, but in others, you may need to look around for a different method (or devise your own).

Upvotes: 0

Dave S
Dave S

Reputation: 136

To solve the problem, matlabFunction was required. The solution looks like this:

syms x y
f = @(x, y) x.*y.^2;
Df = matlabFunction(subs(diff(f,y),y,2));
Int = integral(Df , 0 , 1);

Upvotes: 2

Related Questions