In this first Matlab tutorial, I will try to show you the basics of Matlab user interface, data types, simple functions and mathematical operations. All with basic examples so that anyone with any level of programming knowledge can start using Matlab as a mathematical laboratory.
Matlab User Interface
Start Matlab by a double click on the Matlab icon or else by searching for it under program. Now, there should be a large window containing several smaller. These could for instance be:
- Command Window
- Command History
- and Workspace.
This will of course depend on what version you are currently working in. This is the desktop of Matlab.
Command Window: Here you can write your own command lines and access your own files (m-files), but normally you can also see the output from the calculations in this window.
Command History: All command lines are saved here and can be seen in the window, but the same can be achieved by using the arrow button (up). The past command lines can the be seen in the command window.
Workspace: The variables that have been used or created during the execution will be shown in this window. Here you can see value, bytes and class. When you double click on the variables, the elements of the variables become visible.
These three windows should be the default when you start Matlab.
This can of course be altered by Desktop->Desktop Layout or you can construct your own layout and save it.
Current Directory: The directory where you save your m-files or where you store them. Matlab prefers that you store your m-files in the directory work, but you can of course put them anywhere you want. If you choose to put them in any other directory, you should give the path to the directory by File-> Set Path or select current directory.
Matlab Help Browser
During the tutorials you will need to use the Help Browser in Matlab in order to find out how a certain command works. In the Help Browser you can also find related command lines, examples, description, or help with the syntax.
Try to use help browser by selecting: Help-> Help Browser
This window is divided into two sub-windows. The left window is named Help Navigator. Under Search write sin and press enter. To see the result look above.
Plotting Examples with Matlab
Exercise 1: Plot of sine function
By using the help browser you can find out how the sine function works. Make a plot of a sine function. The interval should be -10 to +10 radians. Each command line that is written in the command window is followed by enter. Note how this is done in the help browser. Now x becomes a variable in Workspace. Double click on x to see which elements are within the variable. If you follow the example x will have 2001 elements. In this case x is a one-dimensional vector. The first command line gives x and the second command line plots the sine function versus the x values in a figure window. The sine function is only evaluated for those x-values that are presented.
Exercise 2: Plot of logarithmic function
Now repeat the above example for a different function using the logarithmic (base 10) function instead. Plot the function for an interval x=0.1:0.01:10. It means that x goes from 0.1 to 10 with a resolution of 0.01 (0.1, 0.11, 0.12, 0.13,…10). Use the help browser and the left subwindow and index to search for a command that gives a logarithm. Maybe you can guess the first letters in this command. The plot should look like figure below. Suitable check values are log(10) and log(1) to see if the plot is reasonable.
Please note that x has changed its elements and size.
Let’s now illustrate how to create an m-file (macro) or if you prefer a small program. Assume that we have to make a number of command lines before we end up with a plot in a figure window. If we make an error in the command line then we have to repeat the command line sequence. A better way should be to put the command line sequence in an m-file and just correct the bad command line there. Execute the m-file simply by writing the name of the m-file in the command window and without the extension .m. In order to let Matlab find the m-file give the path or make the directory where you have stored the m-file to your current directory.
Exercise 3: Creating m-files in Matlab
Open an edit window where we can write the command lines. Click on the white sheet in the menu under File or simply write edit in the command window. Alternatively File->New ->M-file. The following is written in the edit window:
% M-file created by MatlabCorner.COM t=0:0.01:10; % t goes from 0 to 10 in steps of 0.01. y1=sin(t); % everything to the left of the equality sign is an % assignment, y1 is % variable. plot(t,y1), grid % plots y1 versus t and puts a grid on the plot. hold % holds the figure window and allows several plots to be made in the % same figure. y2=sin(2*t); % variable y2 is introduced and calculated. plot(t,y2) % plots y2 versus t in the same figure window as above. title('Exercise 3: matlabcorner.com') % puts a title in our plot. xlabel('time') % gives a label to the x-axis. ylabel('y') legend('sin(t)','sin(2*t)') % puts a box with text for different plots.
Everything that follows the %-character on the same line is regarded a comment and ignored. Also note the semicolon. It prevents output from a command to be printed out in the command window. If the command is a calculation, it is still executed. Save the m-file as exercise3.m in directory work. Run the m-file by writing exercise3 in the command window followed by <enter>. The result should be the same that as in the figure below.
Styling of Matlab Plots
Note that title, xlabel, ylabel and legend could have been performed in the figure window, in the menu under Insert. It looks a bit odd that both curves have the same line styles. This could well be a problem if we did have a problem with trigonometric functions. We will try to solve this. Click on the arrow in the menu of the figure window. Then double click on any of the curves. Enter under Style->LineStyle and change to dotted line. You can also change the color if you want (Line Color).
There is also a possibility to exclude or exchange values in the plot. Let’s illustrate how this is done. Double click on any curve and choose Data->YData->y1 and then Edit Data. Now all plotting values that are used for one of the sine curves are accessible. Change the values to 2 for all indexes from 10 to 20. Take a new look on the plot. This is perhaps not normal procedure in dealing with data, but I am just showing the possibilities with different tools.
Before we end this take a small look Enter View->Camera Toolbar and mark it. Now we get another tools menu in the figure window. By this it is possible with 3D, to rotate the plot, to make it move over the screen and much more. Try it. By now you have constructed your first m-file. There are two sorts of m-files:
- command line
- and function m-files.
Note that an m-file must not begin with a number. The name must not contain dots or space for nothing else than extension.
Exercise 3 was an example of a command line m-file. It only consisted of a number of command lines executed when the name of the m-file was written in the command window. Sometimes you want to use one, several or no argument as input to an m-file.
Such an m-file has the following structure:
Function means it is a function m-file.
Exercise 4: Finding maximum and minimum values in arrays
Let’s write a function file range.m that calculates the difference between the maximum and minimum value in a vector. The file should return a reply. Open an edit window. Create a function file like the one below.
% the m-file is created by MatlabCorner.COM % The m-file calculates the difference between the largest % and smallest element in vector q. function r=range(q) % defines a function file range.m qmax=max(q); % finds the maximum value in the vector q. qmin=min(q); % finds the minimum -value in the vector q. r=qmax-qmin; % gives the value that should be returned.
Save the m-file as range.m. Now please enter a vector q=[ 1 3 5 7 9] in the command window. Run the m-file by simply writing range(q) after the prompt in the command window.
>> range(q) % do not forget to press enter.
Exercise 5: Numerical formats in Matlab
In this example we will investigate numerical format of the output. Check the variable q from the previous exercise. You can find it in Workspace. Double click on it, then we will find ourselves in the Array Editor where we can manipulate elements in the variable q. In our case q is a vector. Right above q you can find Numeric format and Size. Size tells us how large q is. In our case q is a 1×5 vector (1 row and 5 columns). Change it to a 1×4 vector!
Switch the second element in the vector from 3 to 3.0001. Check if there’s any change if you go from a number to a float in q!
Exercise 6: Matrices in Matlab
In previous assignments we have used the concept vector. This is common knowledge for everyone who has read a course in linear algebra. We know that a vector is a special case of a matrix . A two-dimensional matrix is a rectangular table, where all the elements are ordered into rows and columns. A matrix of size mxn has m rows and n columns. In Matlab it could look like the following for a 2×3 matrix:
A = 1 2 3 4 5 6
It is written like:
>> A=[1 2 3; 4 5 6]
The matrix A has 2 rows and 3 columns.
The first row is: 1 2 3 and the second row is: 4 5 6.
The columns are ordered in a similar manner.
Each and every element in A is accessible, by using indices:
What’s the answer to the following ?
Matrices in Matlab does not necessarily only contain real numbers. They can also be complex. We can even have matrices with text as elements. If there is only one row in the matrix => we have a row vector. Only one column in the matrix => a column vector. And finally the special case: a matrix 1×1 is nothing else than a scalar.
What will happen by doing the following?
Try to figure out how the commands size and length works!
Exercise 7: Predefined variables in Matlab
Matlab has some own predefined variables aside from the variables that we make ourselves. You do not need to specify what kind of variables you have introduced. There is no need for any declaration. Matlab separates capital and small letters. No variables may begin with a number, underscore or non-english letters like å, ä and ö. Variables which are numbers are stored in matlab like a float with double precision. The class will be double. Since a computer can not store variables with infinetely high representation we are always limited by the precision of the storage. Predefined variables in Matlab:
ans: The value of the last calculated expression.
eps: Gives computer precision, distance between 1 and closest float.
inf: Defines infinity, defined as 1/0.
i,j: Gives the imaginary unit. Defined as squareroot of -1.
nan: An unidentified number ( Not a Number ).
realmax: Gives the highest float which can be represented by the computer.
realmin: Gives the smallest float which can be represented by the computer.
Write clear in matlabs command window to clear all the variables in the Workspace. Do the following assignment:
>> a=2, b=3
What will be the result of a+b? Of course it becomes 5, but please observe where the result is stored, in the temporary variable ans. This is always true if I make a calculation without any assignment to store the result in.
Write 34+2 Now, ans has a new value. Check eps!
Calculate 1/0+3! What is the answer?
Check the largest and smallest value represented in Matlab!
Multiply the answers by 2. What happens?
Divide ans by ans. Matlab can’t represent this with a number instead it answers NaN.
Working with Complex Numbers in Matlab
Finally let us define complex numbers. Calculate the following:
>> sqrt(-1) % squareroot of -1
We can also write a complex variable as:
>> z=2+3*i % complex variable z: real part 2 and an imaginary part 3.
Try some of the built-in functions in matlab operating on complex numbers:
complex(x,y): Gives a complex number with real- and imaginary-part.
conj(z): Gives the conjugate of z.
real(z): Gives real part of z.
imag(z): Gives imaginary part of z.
abs(z): Gives the absolute value of z.
angle(z): Gives the phase angle of the complex number z.
Observe! There is nothing in Matlab that prevents you from making an assignment where i=5 or whatever.
Exercise 8: Priority of mathematical operators in Matlab
Matlab has five aritmethical operators. These are in order of priority:
- Priority 1: ^ Power
- Priority 2: * Multiplication and / Rightdivision
- Priority 3: + Addition and – Subtraction
If two operators have the same order of priority, the calculations are carried out from left to right. Parenthesis can cancel the order of priority. Evaluate the following:
Matlab gives the answer 4, since the division is carried out before the addition.
Matlab gives the answer 20, since the evaluation starts with power, then we have: 10/5+2*9, after that division and then multiplication, 2+18, and finally addition ans=20
Built-in Mathematical Functions
Matlab is full of mathematical built-in functions which solves arithmetical expressions. We will now list some of the functions from the directory elfun. Type the line below in command window.
>> help elfun
Now we have a long list of mathematical functions, some of them I think you are able to recognize. Below we have some expressions, try to calculate these by using the help in Matlab and specifically the directory elfun. Now calculate some more complex mathematical expressions with these functions (i.e. square root).
Exercise 9: Saving your Matlab sessions
Often one wants to save the data or variables to another occasion. Maybe one wants to save the whole Matlab session. This can be done. Commands are put in a m-file but data or variables are stored in a mat-file (binary file) which can be opened with Workspace Browser. First have a look in the workspace to find out how your varables look like. Then save these in a mat-file.
>> save execution1 % variables will now saved in a mat-file execution1.mat >> clear % clears all variables from the present Workspace. >> load execution1 % restores all variables stored in the execution1.mat
We can also store everything that is displayed in the command window. Like the whole session both the command lines and the output from Matlab, id est the calculations. This can be done by:
>> diary exercise9 % stores the whole session in file exercise9(ascii-file)
Everything that follows from now on in the command window will be stored in the ascii-file exercise9. Write just anything to get some response from Matlab into the command window. diary off % turns of the storage of the session to the file exercise9. Find the file exercise 9 and see if the content in the file is the same that were displayed in the command window!