Matlab Tutorial 1: Hello world, plotting, mathematical functions and file types
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 output_argument=name(input_argument)
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.
>> A(2,1)+A(1,3)+A(2,3) |
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.
>> A(1,1)=12 |
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=2, b=3 |
It is written like:
>> sqrt(-1) % squareroot of -1 |
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.