Thursday, October 15, 2020

[Example] Creating a sliding (animated) tangent plot for a given function (MATLAB)

Basically, this is what we're going to achieve today: 


Why am I interested in this particular example?

It's actually quite simple. This example relates to the notions of slopes and derivatives.

Quite often, in automotive, in case of a failure, we need to ramp-down certain signals (for example, the assistance torque on the steering wheel). We may have requirements stating that the ramp-down must take place with a gradient of x/s or that the signal must reach 0 in y seconds. If we do not have a proper theoretical background, we will not be able to satisfy these requirements.

First of all, what is a derivative (or, better said, what information does it provide us)? Well, simply put, a derivative is a measure of the rate of change of a signal/function, depending on a parameter called the independent variable (for example, speed is a variation of position depending on time). 

The first derivative of a function (no matter the order of that function), will provide us the slope of that function, or the steepness of its graph. By looking at the animation above, we can see that the slope (the magenta tangent) starts quite steep, gradually becomes more gentle, and is quasi-horizontal between -1 and 1, where the function itself is quasi-constant. It then becomes steeper again, when the function starts rising once more. The slope of the tangent line is the same as the derivative of the function at the respective plot point.

What's the mathematical definition of a derivative?

f'(x) = lim h--> 0  (f(x+h)-f(x)) / ((x+h)-x)

What does this formula tell us? 

Well, my interpretation is that if we consider two points that are very close to each other (their difference, h, is infinitesimal), near the graph of the function, we can create a line based on these two points. This will provide us a local tangent to the graph, thus creating the slope of the function for our given point, x. We can also see that this slope is equivalent to delta(y)/delta(x).

So, in order to integrate our knowledge in MATLAB and plot the above figure, we need to:

a) Compute the derivative of our function, in order to get the generic expression of the slope of its tangent line

b) Consider the slope of our tangent line -> slope = (ytg-ytg0)/(xtg-xtg0), where xtg0 will be every point of our x range, and ytg0 the value of our function for that particular xtg0.

c) Write the expression of our tangent as ytg=slope*(xtg-xtg0) + ytg0;

Now we just have to sweep xtg0 through our entire x range in order to recompute the tangent, plot (xtg,ytg), delete it, repeat.


I took some inspiration from this post that shows how to plot a static tangent for a given point, but I've added the extra elements in order to animate the figure. The full code is below (except for the conversion to gif, that one's for another day).


No comments:

Post a Comment