The essence of calculus is the derivative. The derivative is the instantaneous rate of change of a function with respect to one of its variables. This is equivalent to finding the slope of the tangent line to the function at a point.

You already have learned some methods to calculate derivatives of functions and MATLAB can assist you to confirm your results or analyse the behaviour of the derivative graphically.

In this activity we will use the commands syms and diff to calculate derivatives symbolically. Moreover, we will learn the basics of if-else statements and for loops to define MATLAB functions.

Use the MATLAB Live Editor to edit and run this Live Script in your browser or your desktop.

- Read each section carefully.
- Run the code within a section before starting to read the next.
- To run the code from each section, click into the code section and then click on the Run Section button (from the toolstrip) or click on the blue stripe on left side of that section as shown below:

Remark: Run the code of each section from top to bottom, otherwise you may get an error.

- The end of a section is indicated with a thin line, like the next one -

To illustrate how to calculate derivatives in MATLAB, first we create a symbolic expression:

syms x % Define the symbolic variable x

f = 1/(1 + x^2); % Define the symbolic expression, i.e. f(x)

The command

diff(f)

differentiates "f" with respect to "x". Run this section to see the result.

If there are more variables in our function, we can write:

syms x n

f = x^n + 2*n*x;

diff(f)

Remark: You can also specify the variable that you want to differentiate with respect to, i.e. diff(f, n). Try it yourself! Modify the previous code to calculate the derivative with respect to "n".

We can plot together the graphs of

and its derivative

to observe the relationship between these. To do this we write:

x = linspace(-3, 3, 1000);

fun = 1./(1 + x.^2);

Dfun = -2*x./(1 + x.^2).^2;

plot(x, fun, 'r', x, Dfun, 'b', 'LineWidth', 2)

legend('f(x)=1/(1+x^2)', 'f^{\prime}(x)=-2x/(1+x^2)^2')

xlabel('x'), ylabel('y'), grid on

axis([-3,3,-1.5,1.5])

Remark: Here we are using row vectors (also known as arrays) which means that the operations multiplication, division and exponentiation must have the period "." before each operator: *, /, ^. Learn more about it here: Arithmetic operations.

Now run this section to analyse the graphs of and . What do you notice? What do you wonder?

Consider the function

We would like to determine if is differentiable at and 0. But first let's have a look to its graph to observe how it changes. Notice also that is a piecewise function so we need to find a way to define it in MATLAB.

- Define our function with if-else statements.
- Use different conditions for the different ranges and assign appropriate values.

Thus our piecewise function can be defined as follows:

function y = myPiecewiseFunc(x)

if x <= -4

y = 3;

elseif -4 < x && x <= -3

y = -4*x - 13;

elseif -3 < x && x <= 0

y = x^2 + 6*x + 8;

else

y = 8;

end

end

In MATLAB we must declare a new function before using it in our code. In the case of Live Scripts, we can add it at the very end of our document, see Appendix for more details.

x = linspace(-7, 2, 10000); % Define domain

y = zeros(1, length(x)); % A place holder for the range

% Now we evaluate element-by element with a "for" loop

for ix = 1 : length(x)

y(ix) = myPiecewiseFunc(x(ix));

end

% Finally, we just plot it

plot(x, y, 'r', 'LineWidth', 2)

xlabel('x'), ylabel('y'), grid on

title('User-defined piecewise function f(x)')

axis([-7 2 -2 9])

Run this section and analyse the plot. What do you notice? What do you wonder?

Remark: Notice that we have used the for loop to apply our myPiecewiseFunc function to every element in "x". Within any program, you can define sections of code that either repeat in a loop or conditionally execute. On the one hand, loops use a for or while keyword. On the other hand, conditional statements use if or switch, as we did to define our function (see Appendix).

It is well known that the absolute value function

is not differentiable at . This is clear when we have a look to its graph.

We can plot this function using the method described in the previous section. But here we will use a different method so we can also calculate its derivative symbolically with the help of the syms and piecewise commands. Thus we write:

syms x % Define symbolic variable

% Conditionally defined function

g = piecewise( ...

x < 0, -x, ...

0 <= x, x ...

)

% Finally we plot the function

fplot(x, g, 'b', 'LineWidth', 2)

xlabel('x'), ylabel('y'), grid on

title('g(x) - Absolute value')

axis([-3 3 -3 3])

Remark: The three dots "..." tell MATLAB that the code on a given line continues on the next line. It is used so command lines don't stretch out too long to print or read easily.

Since we defined "g" as a symbolic expression we can easily calculate its derivative:

Dg = diff(g)

Run this section and analyse the results. What do you notice? What do you wonder?

In the previous sections we have used the command piecewise to define symbolically as a conditional function. This will allow us to determine if is differentiable at using the left-hand and right-hand derivatives.

Recall that the left-hand and right-hand derivatives of f at are defined by

and

if these limits exist. Then

exists if and only if these one-sided derivatives exist and are equal, i.e.

.

Thus, in MATLAB, first we need to determine symbolically the quotient

and then calculate the left-hand and right-hand limits as follows:

syms x % Define symbolic variable x

% Now define the quotient (g(x)-g(0))/(x-0)

% with the help of a user-defined function absval

quotient = (g - absval(0))/(x - 0);

% Finally, calculate the one-sided limits

limit(quotient, x, 0, 'left')

limit(quotient, x, 0, 'right')

Run this section to see the results. Are these limits equal? Is differentiable at ?

Let's practice what we just learned.

Calculate the derivatives of the following functions:

Write your code here:

Write your code to plot the graph of f here:

Where is f discontinuous? Where is f not differentiable?

Challenge (Optional):

In your notebook

- First calculate the derivative of f.
- Second, determine if f is differentiable at by calculating left-hand and right-hand derivatives. i.e. and .

Then use MATLAB to confirm your results. Use the method from section 3.1.2 to calculate the symbolic derivative and the method from section 3.2 to calculate the left-hand and right-hand derivatives.

Write your code here:

function y = myPiecewiseFunc(x)

if x <= -4

y = 3;

elseif -4 < x && x <= -3

y = -4*x - 13;

elseif -3 < x && x <= 0

y = x^2 + 6*x + 8;

else

y = 8;

end

end

function y = absval(x)

if x < 0

y = -x;

else

y = x;

end

end

% Write your functions after this comment

% Write your functions before this comment

%{

References:

- Declaration of functions

https://au.mathworks.com/help/matlab/ref/function.html

- "If-else" statements

https://au.mathworks.com/help/matlab/ref/if.html

- Loop control statements

https://au.mathworks.com/help/matlab/matlab_prog/loop-control-statements.html

https://au.mathworks.com/help/matlab/ref/for.html

%}