how to calculate the derivative of a function in matlab

In MATLAB, you can use the diff function to calculate the derivative of a function. Here's an example:

main.m
% Define the function
x = linspace(0, 2*pi, 100);
y = sin(x);

% Calculate the derivative
dydx = diff(y) ./ diff(x);

% Plot the function and its derivative
figure;
subplot(2,1,1);
plot(x, y);
title('Function');
subplot(2,1,2);
plot(x(1:end-1), dydx);
title('Derivative');
273 chars
16 lines

In this example, we first define the function y = sin(x). We then use the diff function to calculate the derivative of y with respect to x using the formula (y_{i+1} - y_i) / (x_{i+1} - x_i). We then plot both the function and its derivative using subplot.

gistlibby LogSnag