Applied Matlab Programming

From Uni Study Guides
Jump to: navigation, search

Matlab is used extensively during this course. The tutorials are predominately based on using Matlab for calculations.



To define a variable in Matlab, you type:

>> y = 10

This means 'y' will now be assigned the value from the right side, in which this case is '10'. Entering this will show the following result:

y =

To not show the result, add a semicolon ';' to the end to suppress the output as such:

>> y = 10;

Naming Variables

General rules in naming variables include:

  • All names must start with a letter
  • Can contain letters, numbers and underscores
  • Names are case sensitive
  • Don't use existing functions such as log as a variable name


Variables in Matlab are stored as matrices. This means a vector is a matrix with one row or column and a scalar is one row and one column.

To call an element in a vector or matrix, you type:

>> x(2)
to get the 2nd value of the vector.
>> M(4,5)
to get the element in the 4th row, 5th column of the matrix.

Using a colon ':' instead of a number when calling a matrix will give the entire row or column instead of a single element:

>> M(:,3)
would give a list of elements consisting of all the numbers in the 3rd column.

Creating Arrays

To create an array, type the list of numbers in square brackets '[' and ']' separated by commas ',' as shown:

>> p = [3, 7, 11, 15, 19]

It is possible to create the array using a linear pattern instead of typing all of the elements. Type the first element after the first bracket, then the amount to step the array by, and then the last element of the array, each separated by a colon.

>> q = [3:4:20]
q =
3 7 11 15 19

Another method of creating arrays involves specifying the first and last elements, and then the number of total elements. Type the command 'linspace', and then type the first element, last element and number of total elements between parenthesis '(' and ')' and separated by commas.

>> r = linspace(3, 19, 5)
r =
3 7 11 15 19

Creating Matrices

To create a matrix, type each row with its elements separated by commas, and each row separated by semicolons, all enclosed in square brackets.

>> A = [1, 1, 1, 1; 2, 2, 2, 2; 3, 3, 3, 3]
A =
1 1 1 1
2 2 2 2
3 3 3 3

Matlab has commands which make it easy to create matrices with all zeros and all ones. These are zeros(Rows, Columns) and ones(Rows, Columns) respectively, where Rows and Columns are the number of rows and columns required.

>> g = ones(3)
g =
1 1 1
1 1 1
1 1 1
>> h = zeros(2)
h =
0 0
0 0

To create a square identity matrix, type eye(n), where n is the amount of rows or columns required.

>> i = eye(3)
i =
1 0 0
0 1 0
0 0 1

To transpose a vector or matrix, type transpose(Matrix), where Matrix is the name of the matrix to transpose. It is also possible to transpose by adding an apostrophe after the matrix name.

>> B = transpose(A)
B =
1 2 3
1 2 3
1 2 3


>> B = A'
B =
1 2 3
1 2 3
1 2 3

Creating Strings

Strings are matrices with character elements. They are created by typing a word or phrase in-between two apostrophes as shown:

>> Words = 'Hello Student'
Words =
Hello Student

Mathematical Operations

Mathematical operations are executed according to the same rules as linear algebra. Order of operations also holds true, with parenthesis first, exponentials, multiplication/division and then addition/subtraction last.
Multiplication uses the star '*' between variables. It performs the cross product between vectors and matrices. Adding a period before the star, '.*', performs a dot product between vectors and matrices.
Exponentials use the caret '^'.


Vectorisation allows a vector of values to input into another function to provide another vector as an output. Example:

>> x = [0, pi/2, pi, 3*pi/2, 2*pi];
>> y = sin(x)
y =
0 1.0000 0.0000 -1.0000 -0.0000


Plotting data involves opening a window to present the required graph. To do this, type figure(n), where n is the number of the window (this allows multiple windows to be used at once). The sub plot command allows two graphs to be shown in the same window. Type subplot(Rows, Columns, subplotNumber), where the Rows and Columns are the number of rows and columns of graphs to be shown in the last figure entered into Matlab, and the subplotNumber is the number of the graph to be referenced in the list of sub plots.
Graph of sin(x) on Matlab.PNG

To plot data on a 2D graph, type plot(Data1, Data2), where Data1 and Data2 are the arrays of data required to be graphed. It is important to note that the plot will be graphed onto the last figure window and sub plot that is entered into Matlab.
It is also possible to change the axis that is created by default. To do this, type axis([xmin xmax ymin ymax]), where xmin etc. are the extreme values of the axis. To add a title as well, type title('Here is a title'), where the words in-between the apostrophes are the required title.


>> x = linspace(-2*pi, 2*pi);
>> figure(1)

This opens a window labelled '1'.

>> subplot(3,1,2)

This splits the window in figure 1 into 2 graphs, while selecting the second one of the three.

>> plot(x, sin(x));

This plots 'x' on the horizontal axis and 'sin(x)' on the vertical axis.

>> axis([-2*pi 2*pi -2 2])

This changes the axis to show the data at different positions.

>> title('Graph of sin(x)')

This adds the title above the graph of 'Graph of sin(x)'.


Matlab has different formats to display numbers.
The different formats show different amounts of decimal places.
Bank: 2 decimal places
Short (default): 4 decimal places
Long: 14 decimal places
To change the format, type format long.

Script Files

It is a good idea to use script files, otherwise known as M-files, to type up commands. These scripts can then be used in the command window to execute the commands written in the script file. The benefit of this is the ability to save work, and also the ability to edit it easily if errors were made during the calculations.


A function provides a quick way to do the same calculation multiple times. It takes in an input and provides an output dependent on code that is written for the function. In Matlab, functions can be made in M-files.
To create a function in a script file, begin with creating a M-file with the name of the function. Then type function, making sure this is the first line of the file. Directly after, type Output = FunctionName(Input1, Input2, ...) where FunctionName is the name of the function and InputX is the variable inputs required for the function. Start a new line and then create a function that uses the inputs and creates a results for the variable Output.
The following would be saved in a script named "multiply.m".

function out = multiply(a, b)
out = a * b;

The following would be used in the command window.

>> c = 5;
>> d = 2;
>> multiply(c, d)
ans =

Displaying Functions

To display a function, either the function disp(outVariables) is used, or fprintf(outFormat, outVariables).

To display a string in the command window, fprintf can be used. To display text, type text in-between apostrophes. To add variables in the text, a percentage symbol '%' is added in the text with numbers and letters corresponding to the type of variable and the format required. These include:

%s displays a string
%d displays an integer
%f displays a floating point number
%X.xf where x is the amount of decimal places to be shown
%e displays a floating point number in scientific notation
%g displays number in most compact form, either %f or %e
\n new line
\t tab

The corresponding variable is typed after a comma, after the apostrophes. If multiple variables are placed in the text, the first '%' would correspond to the first variable listed after the apostrophe and so on.

>> a = 10;
>> b = 'string';
>> c = 1.2345;
>> fprintf('This is an example of a %s with the number %d and a truncated floating point number %1.2f.\n', b, a, c)
This is an example of a string with the number 10 and a truncated floating point number 1.23.


Relational Operators

Relational operators are used to compare values. These operators include:

< less than
<= less than or equal to
> greater than
>= greater than or equal to
~= not equal to

These can be used to return a value of either '1' if it is true, or '0' if it is false.

>> a = (5 > 1) + (3 < 1)
a =

Logical Operators

Logical operators are used with relational operators to combine their solutions.

& if both values equal '1' it produces '1', else, '0'.
| if either values are '1' it produces '1', else, '0'.
~ if the value is '0' it produces '1', else, '1'.


>> a = 0 & 0
a =
>> a = 1 | 0
a =
>> a = ~1
a =

Logical Functions

A logical function that is useful is find(). It allows a search of arrays to find the reference to the values that fit an expression.

>> A = [3, 5, 2, 8, 7, 1, 9];
>> B = find(A > 3)
B =
2 4 5 7


A loop is used to loop a function with a varying input. There are two types of loops, for and while. They can be written in M-files, and

For Loops

A for loop involves applying a function or a set of statements for a certain set of values. It requires a set of values for the loop to go through as it loops through the functions and statements, which is defined directly after the "for". To display the results of the loop, the disp() function is used. The loop then ends with end.

This is typed into an M-file named "ALoop".

for t = [1, 3, 5, 7]
g = t + 5;

This is typed into the command window.

>> ALoop

While Loops

A while loop applies functions or a set of statements while a certain condition is met. To use a while loop, first set a variable to be the counter for the loop, which is then incremented in the loop until it meets the exit condition. Then type while with the exit condition directly after it, with the functions or statements below, finalising it with incrementing the counter and typing end.

This is typed into the M-file named "ALoop2".

a = 1;
while a < 4
a = a + 1;

This is typed into the command window.

>> ALoop2

If Statements

An if statement/condition is a conditional statement that allows a certain function to be run if certain conditions are met. The basic if statement includes if with an expression directly after it. If this holds true, the statement below it will be executed. If the expression is false, it will skip the statements below, unless an else or elseif is present. An elseif allows another if statement to be done if the first statement was false, while the else statement allows the following statements to be executed if the previous expressions were false. At the end of an if statement, type end.


>> b = 5;
>> if b > 6
a = 2;

(Note: Continuing typing on a new line without executing the previous line can be done by pressing shift + enter)

elseif b > 3
a = 1;
a = 0
>> a
a =

Switch and Case

Switch and case allow a certain value to be displayed depending on the input value. It is used in conjunction with the function input(), where the text inside the parenthesis are displayed in the command window and waits for user input. Type switch followed by the variable that includes the input value, and then type case followed by a possible input value. Then type what is required to be shown if the case specified holds true. Use otherwise to show what is required if the input does not match a case.


>> daytime = input('Is it Light or Dark outside, written in single quotes:');
switch daytime
case 'Light'
disp('It is day time.')
case 'Dark'
disp('It is night time.')
disp('I don't know.')

This will be shown, requesting an input.

Is it Light or Dark outside, written in single quotes: 'Light'
It is day time.

Break Command

The break command allows an exit from a loop under a certain condition before a loop has actually completed. Type break on a new line where it is required. This can be included in a loop where an if statement is used, for example, if a certain value is found, break the loop.


This is the end of this topic. Click here to go back to the main subject page for Numerical Methods & Statistics.

Personal tools