Linear Algebra and Programming Skills

Dr Jon Shiach, Department of Computing and Mathematics, Manchester Metropolitan University

MATLAB Basics

Learning Outcomes

On successful completion of this page readers will be able to:

MATLAB Live Scripts

The materials which will help you to learn how to program in MATLAB use MATLAB Live Scripts which allow you to type in commands and see the results within the same live document. MATLAB live scripts have the file extension .mlx and can be opened either by double clicking on the file in a file manager or opened within MATLAB.

Installing MATLAB on your own machine

You will have access to MATLAB on the machines in the university PC labs but you may find it useful to download and install MATLAB on your own machine. To do this click on the link below and follow the installation instructions.
MATLAB installation instructions

Examples and exercises

These materials have a number of examples and exercises for you to try out. The examples, similar to the ones above, a designed to demonstrate how the various MATLAB commands work. The exercises give you an opportunity to put into practice what you have learned. The solutions to the exercises can be found on Moodle. In programming, there can be many different ways of achieving the same result, don't worry if your solutions do not exactly match the ones provided.

Using MATLAB Live Scripts

When you open a MATLAB Live Script you should see a screen similar to below (this is the Mac version of MATLAB but the Windows version should look similar). Notice that a live script consists of text cells and code cells. A code cell allows us to write and execute commands and see the result. The code cells are executed by clicking on the Run button in the toolbar or by pressing the F5 key.
For example, enter the following command into the code cell below and run the live script.
seconds_in_a_day = 24 * 60 * 60
seconds_in_a_day = 24 * 60 * 60
seconds_in_a_day = 86400
Here we have computed the number of seconds in a day, stored it as a variable and returned the result. Variables that we have defined in one cell can be used in later code cells. For example, enter the following command and run the live script once again.
seconds_in_a_week = 7 * seconds_in_a_day
seconds_in_a_week = 7 * seconds_in_a_day
seconds_in_a_week = 604800

Basis arithmetic operations

We will begin with using MATLAB to perform basic arithmetic operations since these are fundamental to computer programming (it is helpful to think of your computer as a very powerful calculator). The arithmetic operators used to perform the basic operations are shown in the table below.
Example 1
Use MATLAB to calculate the following:
(i)
3 + 4
3 + 4
ans = 7
(ii)
4 - 7
4 - 7
ans = -3
(iii)
5 * 3
5 * 3
ans = 15
(iv)
2 / 9
2 / 9
ans = 0.2222
(v)
2 ^ 5
2 ^ 5
ans = 32
(vi) ( means the remainder when x is divided by y)
mod(23, 4)
mod(23, 4)
ans = 3

Order of precedence of operations

MATLAB follows the standard rules for order of operations, i.e., BODMAS: Brackets > Orders (powers) > Division, Multiplication > Addition, Subtraction.
Brackets are used to override this where necessary.
Example 2
The command below calculates the value of the expression . Enter it into the code cell below and run the live script.
1/(2 + 3)
1 / (2 + 3)
ans = 0.2000
Omitting the brackets from this command results in the command below. Enter this into the code cell below and run the live script.
1/2 + 3
1 / 2 + 3
ans = 3.5000
This has calculated the value of .

Exercise 1 - Basic arithmetic operations

1. Use MATLAB commands to evaluate:
(a) ;
2 - (3 + 6)
ans = -7
(b) ;
2 * (5 - 8 * (3 + 6))
ans = -134
(c) ;
2 * (2 - 2 * (3 - 6 + 5 * (4 - 7)))
ans = 76
(d) ;
2 * (5 - 4 * (3 + 8)) / (3 * (4 - (3 - 5)))
ans = -4.3333
(e) ;
2 * 4 ^ 5/(81 - 5 ^ 2)
ans = 36.5714
2. Use a MATLAB command to calculate the remainder of 14151 divided by 571.
mod(14151, 571)
ans = 447

Mathematical functions

MATLAB has many of the standard mathematical functions such as square roots, logarithms, trigonometric functions etc. built-in. The MATLAB commands for some of these is shown in the table below.
Note:
Example 2
Evaluate the following:
(i)
sqrt(9)
sqrt(9)
ans = 3
(ii)
cos(pi / 4)
cos(pi / 4)
ans = 0.7071
(iii)
exp(2)
exp(2)
ans = 7.3891
(iv)
factorial(4)
factorial(4)
ans = 24
(v)
round(1.6)
round(1.6)
ans = 2
(vi)
floor(1.6)
floor(1.6)
ans = 1

Exercise 2 - Using mathematical functions

3. Use MATLAB commands to evaluate:
(a) ;
sqrt(3 ^ 2 + 4 ^ 2)
ans = 5
(b) ;
cos(pi)
ans = -1
(c) ;
asin(1)
ans = 1.5708
(d) ;
log(exp(2))
ans = 2
(e) .
log10(1000000)
ans = 6

Variables

Variables are used to store information which can be retrieved elsewhere in a computer program. To define a variable in MATLAB we use the equals sign =. For example
a = value of a
Once a variable has been defined the information stored in it can be used in other commands in the program that follow the variable declaration.
Example 3
The commands below define the 3 variables x, y and z and calculates their sum. Enter them into the code cell below and run the live script.
x = 1
y = 2.5
z = -3
 
x + y + z
x = 1
x = 1
y = 2.5
y = 2.5000
z = -3
z = -3
 
x + y + z
ans = 0.5000

Suppressing output

Note that MATLAB always returns the value of a command by default. To suppress this use a semi-colon ; at the end of the line. This is useful for programs that include multiple commands.
Example 4
The commands below perform the same calculations as example 3 but semi-colons are used to supress the output of the variables x, y and z. Enter them into the command cell below and run the live script.
x = 1;
y = 2.5;
z = -3;
 
x + y + z
x = 1;
y = 2.5;
z = -3;
 
x + y + z
ans = 0.5000
Note that when we defined the variables x, y and z MATLAB did not output their values.

Variable names

A MATLAB variable can have a short name (e.g., x and y) but sometimes it is advisable to use longer descriptive names so that your program is easier to understand (e.g., distance, seconds_in_a_minute). Variable names must adhere to the following rules:
Example 5
Enter the following command into the code cell below and run the live script (MATLAB will return an error, don't worry).
1st_variable = 2;
first_variable = 2;
To overcome this we need to use a different variable name, e.g.,
first_variable = 2;

Checking which variables have been defined

To check which variables have already been defined we can use the whos command (help page).
Example 6
The output of the whos command below lists all of the variables defined so far in this live script.
whos
Name Size Bytes Class Attributes ans 1x1 8 double first_variable 1x1 8 double seconds_in_a_day 1x1 8 double seconds_in_a_week 1x1 8 double x 1x1 8 double y 1x1 8 double z 1x1 8 double

Clearing variables

Once declared, variables will remain stored in the memory until cleared using the clear command (help page) which will clear all variables. To clear specific variables we list them after the clear command
clear % clears all variables
clear variable1 variable2 % clears only variable1 and variable2
Having variables declared from a previous program is a common source of bugs in MATLAB. Therefore it is always advisable to begin a program or code cell with the clear command.
Example 7
The whos command below returns nothing since all variables were cleared using the clear command.
clear
whos

Types of variables

MATLAB uses the following types of variables:
When defining a variable MATLAB will automatically use the appropriate variable type depending on the value assigned.
Example 8
Define the following variables:
(i)
a = 2
a = 2
a = 2
(ii)
b = 1.5
b = 1.5
b = 1.5000
(iii)
c = 5e9 % floating point exponential number
c = 5e9
c = 5.0000e+09
(iv)
d = 2 + 3i
d = 2 + 3i
d = 2.0000 + 3.0000i
(v)
e = true
e = true
e = logical
1
(vi)
f = 'this is a string'
f = 'this is a string'
f = 'this is a string'

Exercise 3 - Using variables

4. Write a MATLAB program that uses variables to convert a temperature in degrees Centigrade C to degrees Fahrenheit F using the formula
What is the equivalent temperature in Fahrenheit of ?
C = 100;
F = 9 / 5 * C + 32
F = 212
5. Write a program that calculates the length of the hypotenuse of a right-angled triangle given the lengths of the two other sides are 2 and 3.
side1 = 2;
side2 = 3;
hyp = sqrt(side1 ^ 2 + side2 ^ 2)
hyp = 3.6056
6. Write a program that calculates an angle of a right-angled triangle in degrees given the lengths of the adjacent and opposite sides are 4 and 5.
adj = 4;
opp = 5;
angle = atan(opp / adj) * 180 / pi
angle = 51.3402

Formatting code

It is good programming practice to format your code so that it can be easily read. There are a number of things which you can do to help with this.

Spaces

In a MATLAB program spaces are ignored; however it is common practice to use spaces either side of the arithmetic operators so that it is more readable. It is also advisable to separate blocks of code with a blank line.
Example 9
The two commands below return the same value but the second one is easier to read than the first.
1*2+3*4+5/6
 
1 * 2 + 3 * 4 + 5 / 6
Enter them into the code cell below and run the live script.
 

Comments

A comment in a program is text that is ignored by MATLAB when the code is executed. Comments are useful to helping people understand the program. Comments in MATLAB are declared using the % symbol such that any text on the same line to the right of % is ignored.
Example 10
The program below makes use of comments. Note how the lines of the program are spaced out to improve the readability of the code. Blank lines are ignored by MATLAB.
% This program calculates the sum
% of two numbers
 
clear
x = 4; % first number
y = 7; % second number
 
% calculate the sum of the two numbers
x + y
Enter it into the code cell below and run the live script.
% This program calculates the sum
% of two numbers
 
clear
x = 4; % first number
y = 7; % second number
 
% calculate the sum of the two numbers
x + y
ans = 11

Splitting long lines of code

To split a line of code we use ... (three dots). This is useful when a single line of code requires a lot of horizontal space.
Example 11
The program below uses ... to split the line of code that calcualtes the sum of x, y and z.
clear
 
% Define variables
x = 2;
y = 3;
z = 4;
 
% The code below has been split over two lines (rather uneccessarily)
sum_xyz = x + y ...
+ z
Enter it into the code cell below and run the live script.
clear
 
% Define variables
x = 2;
y = 3;
z = 4;
 
% The code below has been split over two lines (rather uneccessarily)
sum_xyz = x + y ...
+ z
sum_xyz = 9

Printing output

To output text or the value of a variable within a MATLAB program we can use the fprintf command (help page).
fprintf('some text')
Example 12
The code below outputs 'hello world'.
fprintf('hello world')
Enter it into the code cell below and run the live script
fprintf('hello world')
hello world

Printing text and numbers

Sometimes it is desirable to be able to output text alongside numbers. This is known as formatted output and can be done using the following
fprintf('some text <format specifier> some more text <format specifier>.', x, y)
The <format specifier> in the code above is one of the following
Note that in the above when a is 1 MATLAB will use the minimum number of characters required to display the number.
Example 13
The following are examples of formatted output using the fprintf command. Enter each of them into the code cells and run the live script after each one.
fprintf('The value of e to 10 decimal places is %1.10f.', exp(1))
fprintf('The value of e to 10 decimal places is %1.10f.', exp(1))
The value of e to 10 decimal places is 2.7182818285.
Here were have used %1.10f for the format specifier. This means we have outputted the value of e which is a floating point number (a decimal) to 10 decimal places using the minimum number of characters required.
fprintf('Then, shalt thou count to %10i, no more, no less.', 3)
fprintf('Then, shalt thou count to %10i, no more, no less.', 3)
Then, shalt thou count to 3, no more, no less.
Here the integer 3 was printed using 10 character spaces so there are 9 empty spaces to the left of the 3.
fprintf('The speed of light is %1.2e m/s.', 2.9979e8)
fprintf('The speed of light is %1.2e m/s.', 2.9979e8)
The speed of light is 3.00e+08 m/s.
Here the floating point exponential number was printed to 2 decimal places using the minimum number of characters required.
name = 'Andrew Wiles';
year = 1995;
fprintf('Fermats last theorem was proved by %20s in %1i.', name, year)
name = 'Andrew Wiles';
year = 1995;
fprintf('Fermats last theorem was proved by %20s in %1i.', name, year)
Fermats last theorem was proved by Andrew Wiles in 1995.
Here the character string Andrew Wiles was printed using 20 character spaces.
Note that often it takes a bit of trial and error to get the right spacings in your program. Don't be afraid to experiment with your code.

Printing multiple lines

It is possible to print multiple lines with a single print statement using the command \n which moves to the next line.
Example 14
The command below uses a single fprintf comand to print multiple lines.
fprintf('This text \nis printed\n\non multiple line \n\n\nusing a single fprintf command.')
Enter it into the code cell below and run the live script.
fprintf('This text \nis printed\n\non multiple line \n\n\nusing a single fprintf command.')
This text is printed on multiple line using a single fprintf command.

Printing long lines of text

To print long lines of text we can use an array of character strings in the fprintf command.
fprintf([ 'string1', ...
'string2', ...
'string3' ])
Example 15
The command below uses an fprintf command to output an array of character strings.
fprintf([ 'some text, ' ...
'some more text ' ...
'in the same print command'])
Enter it into the code cell below and run the live script.
fprintf([ 'some text, ' ...
'some more text ' ...
'in the same print command'])
some text, some more text in the same print command

Exercise 4 - Printing output

7. Output the value of e to 20 decimal places.
fprintf('%1.20f', exp(1))
2.71828182845904509080
8. Write a program that uses the formula below to calculate the monthly repayments and total value of a mortgage of £100,000 taken out over 20 years at a fixed annual interest rate of 5%.
where C is the monthly repayment amount, r is the monthly interest rate, P is the amount borrowed, n is the number of monthly repayments. Use fprintf commands to output the loan amount, the duration of the mortgage, the annual interest rate, the monthly repayments and total value of the mortgage.
P = 100000; % amount borrowed
r = 0.05 / 12; % monthly interest rate
years = 20; % the duration of the mortgage in years
n = years * 12; % the duration of the mortgage in months
 
C = r * P / (1 - (1 + r) ^ (-n));
 
fprintf(['Loan amount: £%0.2f\n' ...
'Mortgage duration: %0i years\n' ...
'Monthly repayments: £%0.2f\n' ...
'Total mortage value: £%0.2f'], P, years, C, n * C)
Loan amount: £100000.00 Mortgage duration: 20 years Monthly repayments: £659.96 Total mortage value: £158389.38
9. Write a program that calculates the number of years, weeks, days and minutes that are are equivalent to 1 million seconds and 1 billion seconds. Output the answer in a single meaningful sentence.
Hint: The floor and mod commands may come in useful here.
% Conversion quantities
seconds_in_a_minute = 60;
seconds_in_an_hour = 60 * seconds_in_a_minute;
seconds_in_a_day = 24 * seconds_in_an_hour;
seconds_in_a_week = 7 * seconds_in_a_day;
seconds_in_a_year = 365 * seconds_in_a_day;
 
% 1 million seconds
x = 1000000;
 
years = floor(x / seconds_in_a_year);
remaining = mod(x, seconds_in_a_year);
weeks = floor(remaining / seconds_in_a_week);
remaining = mod(remaining, seconds_in_a_week);
days = floor(remaining / seconds_in_a_day);
remaining = mod(remaining, seconds_in_a_day);
hours = floor(remaining / seconds_in_an_hour);
remaining = mod(remaining, seconds_in_an_hour);
minutes = floor(remaining / seconds_in_a_minute);
remaining = mod(remaining, seconds_in_a_minute);
 
% Output the results
fprintf(['%1i seconds is the same as %1i years, %1i weeks, ' ...
'%1i days, %1i hours, %1i minutes and %1i seconds.'], ...
x, years, weeks, days, hours, minutes, remaining)
1000000 seconds is the same as 0 years, 1 weeks, 4 days, 13 hours, 46 minutes and 40 seconds.
% 1 billion seconds
x = 1000000000;
 
years = floor(x / seconds_in_a_year);
remaining = mod(x, seconds_in_a_year);
weeks = floor(remaining / seconds_in_a_week);
remaining = mod(remaining, seconds_in_a_week);
days = floor(remaining / seconds_in_a_day);
remaining = mod(remaining, seconds_in_a_day);
hours = floor(remaining / seconds_in_an_hour);
remaining = mod(remaining, seconds_in_an_hour);
minutes = floor(remaining / seconds_in_a_minute);
remaining = mod(remaining, seconds_in_a_minute);
 
% Output the results
fprintf(['%1i seconds is the same as %1i years, %1i weeks, ' ...
'%1i days, %1i hours, %1i minutes and %1i seconds.'], ...
x, years, weeks, days, hours, minutes, remaining)
1000000000 seconds is the same as 31 years, 37 weeks, 0 days, 1 hours, 46 minutes and 40 seconds.
10) Use suitable fprintf commands to produce the following table where each value is printed using 8 character spaces and 4 decimal places.
x | sqrt(x) | exp(x) | ln(x) | cos(x)
------------------------------------------------------
1.0000 | 1.0000 | 2.7183 | 0.0000 | 0.5403
2.0000 | 1.4142 | 7.3891 | 0.6931 | -0.4161
5.0000 | 2.2361 | 148.4132 | 1.6094 | 0.2837
fprintf([' x | sqrt(x) | exp(x) | ln(x) | cos(x)\n' ...
'------------------------------------------------------\n' ...
'%8.4f | %8.4f | %8.4f | %8.4f | %8.4f\n' ...
'%8.4f | %8.4f | %8.4f | %8.4f | %8.4f\n' ...
'%8.4f | %8.4f | %8.4f | %8.4f | %8.4f\n'], ...
1, sqrt(1), exp(1), log(1), cos(1), ...
2, sqrt(2), exp(2), log(2), cos(2), ...
5, sqrt(5), exp(5), log(5), cos(5))
x | sqrt(x) | exp(x) | ln(x) | cos(x) ------------------------------------------------------ 1.0000 | 1.0000 | 2.7183 | 0.0000 | 0.5403 2.0000 | 1.4142 | 7.3891 | 0.6931 | -0.4161 5.0000 | 2.2361 | 148.4132 | 1.6094 | 0.2837