Credit portal




How to take derivative in matlab

how to take derivative in matlab

Start Matlab by going to the Start menu and finding Matlab 7.1 (or whatever version you have.)   You should see a window pop up that looks like:

The various parts of the window are:

The “Command Window” is where you type in commands… it acts just like a calculator.   The Matlab commands help and lookfor are particularly useful for finding stuff out.   Try them out.   lookfor searches help files So, if you wanted to do something with fuzzy logic, try lookfor fuzzy and it will tell you a bunch of functions.   Then pick one that sounds useful and type help <whatever> and it will tell you more about that function.   See below:

You can define variables and do operations on them just like on a calculator.   The “workspace” area on the top left will show you all your currently defined variables.

One thing you will want to do early on is change the working directory.    Matlab defaults to a directory under the Matlab main directory.   You probably want to work in a subfolder of your home directory.   Change your working directory by mousing the path bar at the top of the screen, as shown in the top image on this page.   You can click the three dots icon to the right of that path bar to browse to your favorite working directory.   This is the directory Matlab will save and load data files from and look for user defined functions in.

There are many many many useful functions in Matlab that do everything from basic arithmetic to control system design to image processing.   In many ways, being good at Matlab means knowing a ton of useful functions.   Go look in the help menu to see the wealth of things available to you.

You define vectors in Matlab with the syntax:

Which is a column vector.   Vector multiplication is defined according to normal linear algebra rules… so a 3x1 vector times a 1x3 gives you a 3x3 matrix and so on.   See example below.

Matrices can be defined similarly, separating rows with semicolons and columns with spaces:

>>A= [1 2 3;4 5 6;7 8 9]

You can multiply matrices and vectors just like scalars.   You can also use complex numbers by using the built in constants j and i.   pi is also a built in constant.   See some examples below:

Also notice here the scientific notation Matlab uses.   After I multiply A*A (matrix multiplication), it reports the answer with 1.0e+002 at the top… meaning that everything in the matrix is multiplied by 100.   Hence, A(1,1) is 6+3i.

If you want to perform an arithmetic operation element-by-element, rather than doing true vector or matrix mathematics, use the operator with a dot in front of it.   What I mean is,

Be careful you are doing what you mean to do.   Often in matlab a vector is really a list of scalars (say from data you gathered in the lab) and you may want to, say, multiply the corresponding samples in the two channels of data together.   You would then use the .* operator, not the * operator.   The Matlab window showing the above operations compared is shown below:

One thing that Matlab is useful for is plotting data.   In the Matlab window below I will plot a sine function, by first creating a vector of time values t. which goes from 0 to 1 and has 1000 points.   (I use the linspace function, which generates a linearly spaced list of values.   Type help linspace for more information.)   I then define a vector x which is equal to sin(4*2*pi*t).   Notice that I put a semicolon after the commands for creating t and x.   This tells Matlab to just perform the operation, but not report the result.   If I had left the semicolon off, then a thousand values will scroll past me, making a big mess.   You can put a semicolon at the end of any command to tell Matlab to be quiet and not report the result.   After defining t and x. I then use the plot command to plot one verses the other:

The following figure window pops up.

You can copy Matlab figures to the clipboard from the edit menu in the figure window, save them to Matlab figure files or to image files of various types (eps, jpeg, etc.) for including in documents.   You can also edit all the properties (such as axis labels, font, line color, width, and style, and so forth) by selecting the items in the window using the arrow tool, right clicking, and changing properties.   You can zoom in using the magnifying glass tool, and zoom back out by double clicking with the zoom tool.

Another thing I can do in Matlab is compute derivatives and integrals numerically.   The gradient function computes numerical derivatives, and the cumtrapz uses the trapezoidal rule to cumulatively integrate a signal.

  Type help gradient   or help cumtrapz for more information.   See the example below:

Where I have done a couple of new things.   The gradient function needs the data (x) and the spacing between data points (1/1000 in this case).   The cumtrapz function needs the data ( x ) and the thing to integrate with respect to (t ).   The hold on command tells Matlab to hold the plot, so that when I do the next plot commands it keeps my original sine curve on there.   If I didn’t say hold on. Matlab would just wipe out the original curve when it plotted the new one.   In the plot commands, I have included a string which tells what color to make the line ‘r’   for red, and ‘g’ for green (see help plot for more information).   This generates the following figure:

Where the derivative is in red and the integral in green.   Since the frequency of this sine curve is 4pi, the derivative is larger amplitude than the original signal and the integral is smaller amplitude (it looks flat, but if I zoom in, you can see that it is also a cosine wave as it should be):

If you just want to compute the definite integral of a signal, you can do so using the trapz command, which uses the trapezoidal rule.   For instance, to find the total integral of the original sine wave I could do the following:

Which is very close to zero.   The 2e-17 value produced is a numerical error due to the numerical nature of the computation.   Expect to see such things in Matlab… most everything is done numerically.

Matlab Session 2

In the Matlab session taught Feb 13-15, 2006, I attempted to rapidly go through:

1. M-files

These are scripts which contain a sequence of Matlab commands.   They operate exactly the same way as typing the commands one after the other at the Matlab prompt.   They are created by going File|New|M-file, which will bring up the Matlab editor.   Save the file wherever you like.   It is simply a text file with a .m extension.   They can be edited by any program which reads text files, although the Matlab editor is probably best since it highlights/colorizes the text appropriately.   You can run a m-file from the Matlab command prompt by typing the name of the file (without the .m extension).   It will operate just like any other Matlab command.   Make sure your working directory is set to the directory that the m-file is in, or Matlab won’t find it!!

In the Matlab editor, type all the commands you want and then save the file.   You can run it from the Matlab prompt.   For example, let’s say we wanted to create an m-file to solve the quadratic equation:

But you want to handle the case where A=0 differently or you will get a divide by zero error.   Below you can see an m-file I wrote which solves this problem.   It is called quadratic1.m .

If you save it in the working directory and run it, you should see:

Let’s say we wanted to include a for loop to let A=-5,-4,-3…5, and plot all the roots of the quadratic equation for each of these values.   We could do this using the following m-file:

If I run quadratic2 at the Matlab prompt, I see the following figure appear:

Where we can see the two real roots for A<0, the single root x=-1.5 for A=0, and then the complex conjugate pairs moving off the real axis for A>0.

These two m-files give examples of how to use for loops and if statements.   NOTE:   mfiles are exactly like typing at the command prompt;   hence if you alter a workspace variable in your mfile, it will change it in the workspace.   Similarly, workspace values are available to your mfile.

2. Functions

Functions are similar to m-files, but there is a well-defined input and output interface.   A function takes arguments and returns something.   It can take multiple scalar, vector, or matrix arguments, and return any number of things as well.   Type

>> help function

At the Matlab prompt for more information.   As an example, I can set up my quadratic equation solver as a function in the following way:

Some important things to note about functions:

(1) The filename for the function must be the same as the function name (here, both are quadratic )

(2) The function has a “local scope”… it does NOT have access to variables in the workspace.   If you want it to have access to workspace variables, you must define the variables as global both inside the function and in the workspace (>> help global for more information).

So, if I run this function at the Matlab prompt, I will see:

3. Solving systems of algebraic equations

Category: Bank

Similar articles: