An Introduction to MATLAB Programming

A program consists of a sequence of instructions to the computer. These instructions are used to describe the types of data to be used, the manipulations desired of this data, and how results are presented to the user of the program.

In MATLAB the commands can either either be entered directly into the workspace or they can be saved to a file - when the file is called (at the MATLAB command prompt) the instructions are executed automatically. This latter method is potentially much more powerful.

Variables

Variables are used to hold values while the program is running (similar to a memory in a calculator). Most variables can be given new values at any time. That is, the following extract of code is perfectly valid:
  ...
  x = 1.0
  y = 2*x
  x = 10.0
  z = x/2.0
  ...

Code is much more readable if reasonable names are given to all variables and numeric constants. For example, the following code

  Pi = 3.1416
  ...
  radians = degrees / (2*Pi)
  ...
is much more readable and intuitive than
  ...
  radians = degrees / 6.2832
  ...

Note that MATLAB is case sensitive, e.g. Pi is a different variable name to pi.

One major property of real numbers (otherwise known as floating point numbers) on a computer is that many can not be represented exactly. Computers use binary numbers internally so only numbers that are some exact multiple of small powers of 2 can be represented accurately. For example, 1/2 = 0.5, 1/4 = 0.25, 1/8 = 0.125, etc can be represented exactly. However, numbers such as 1/3 = 0.3333 and (maybe surprisingly to people used to working in a decimal system) 1/10 = 0.1 can not be represented exactly on a computer. For example:


>>  format long
>>  x = 0.1
>>  y = 1
>>  z = y - (x+x+x+x+x+x+x+x+x+x)
The output is:
z = 
  1.387778780781446e-16
Though the value of z is very small the answer should have been zero. This error is known as rounding error (or round-off error) and can, in some sequences of calculations, accumulate quickly, sometimes leading to completely erroneous results.

Rounding error is more likely to appear when similar values are subtracted from each other.

Expressions

Calculations are performed by specifying expressions. An expression is equivalent to a mathematical equation where the left hand side is a single variable which will contain the value of the right hand side. The equals sign (=) is an assignment (as opposed to a mathematical statement of equality) so that the expression
x = x + 1
means that the variable x is given (assigned) the value that results from adding 1 to x. This is different from a mathematical equation which would allow us to subtract x from both sides of the equation, ending up with "0 = 1" which is definitely not true!

The following standard mathematical operators are all available in MATLAB:

+  add two values together
-  subtract second value from first
*  multiply
/  divide
^ raise first value to second value
In addition many standard mathematical functions (sin, cos, log, exp, ...) are available. Note: the log function returns the natural log (ln). If you want the base 10 log, use the function log10. Functions are used by putting the argument in ()'s, as in "sin(x)."

Operators have different precedence. This means that some operators are used before others when evaluating an expression. For example: "2+3*4" will evaluate to 14 and not 20. This is similar to many calculators, If 20 were the desired result, you would type "(2+3)*4". The power operator (^) has the highest precedence (i.e. it's evaluated first), followed by multiplication and division, and last come addition and subtraction. A more detailed explanation of the use of mathematical operators is given in a later section .

Simple programs

A MATLAB program consists simply of the name and then the actual steps you wish the program to perform. This can be seen in the example program shown below. The execution of a program proceeds from the first executable statement through to the end of the program (there are, however, several exceptions to this rule. See section on program control). Each statement is executed in turn.
% Velocity
% This program calculates the average speed of an object

time  = 4.7 ;                          % The variable "time" is assigned a value
distance = 2*time^3 - 5*time + 18.3;   % Distance form origin is calculated
velocity = Distance/time               % The average velocity is calculated

% End of program
You'll have noticed in the example program that there is a description attached to almost every line of the program. These descriptions, known as comments, are indicated by a starting percentage sign (%). Comments can appear anywhere after the end of a command or by themselves on a line. Everything after the percentage sign is ignored by MATLAB. In MATLAB any comments at the beginning of the file will be called if the user asks for help on the program.

Comments are intended to help the person reading the code understand the function of the code. You should always put comments in your programs, even if you are the only one that will be looking at that code. It is a fundamental law of nature that a program doesn't appear as intuitively obvious to even the programmer an hour after it was written! Comments are absolutely necessary and their liberal use is highly recommended.

Related to comments is the actual indentation of each line. You should also consider indenting certain lines to make it clear how they fit in with the rest of the code. The use of indentation will become clearer when we discuss controlling the flow of execution in a program.

An Exercise

You should now attempt the exercise associated with this section. You should have already tried out the introductory exercise.

Click HERE for next section.