Matlab Tutorial 1: Hello world, plotting, mathematical functions and file types


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:

>> A(2,1)+A(1,3)+A(2,3)

Matlab gives the answer 4, since the division is carried out before the addition.

>> A(1,1)=12

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.

>> a=2, b=3

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).

Let us see if we have round off functions in Matlab. Get aquatinted with the functions round, fix, floor and ceil.

>> sqrt(-1) % squareroot of -1

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.

>> z=2+3*i % complex variable z: real part 2 and an imaginary part 3.

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!

Pages: 1 2 3 4 5