MATLAB Answers

## Create an anonymous function after Symbolic differentiation

Asked by Giorgos Papakonstantinou

### Giorgos Papakonstantinou (view profile)

on 13 May 2013
Accepted Answer by Sean de Wolski

### Sean de Wolski (view profile)

I want to differentiate a function f and the calculate the derivative of f at value of x. How can I do that? for example:

```syms x
```
```f=@(x) x^3+3*x+1;
```
```g=diff(f(x))
```

Preferably I would like to create a function handle of the derivative and then calculate the derivative at x.

## 2 Answers

### Sean de Wolski (view profile)

Answer by Sean de Wolski

### Sean de Wolski (view profile)

on 13 May 2013
Accepted answer

Almost there!

```gfun = matlabFunction(g)
g(2)
```

#### 2 Comments

Giorgos Papakonstantinou

### Giorgos Papakonstantinou (view profile)

on 13 May 2013

Thank you. Although it should be gfun(2).

Sean de Wolski

### Sean de Wolski (view profile)

on 13 May 2013

Rule #1 of Answers: if you rewrite something from MATLAB, you will make a typo :)

### Iman Ansari (view profile)

Answer by Iman Ansari

### Iman Ansari (view profile)

on 13 May 2013

Hi.

```syms x
f=@(x) x^3+3*x+1;
g=diff(f(x))
h=@(y) subs(g,y)
```

#### 2 Comments

Giorgos Papakonstantinou

### Giorgos Papakonstantinou (view profile)

on 13 May 2013

Thank you! But then if I ask for g(2) then I get this error:

```Error using mupadmex
Error in MuPAD command: Index exceeds matrix dimensions.
```
```Error in sym/subsref (line 1389)
B = mupadmex('symobj::subsref',A.s,inds{:});
```
Giorgos Papakonstantinou

### Giorgos Papakonstantinou (view profile)

on 13 May 2013

with h(2) it works... thank you!

#### Join the 15-year community celebration.

Play games and win prizes!

Learn more

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

### MATLAB Academy

New to MATLAB?

Learn MATLAB today!