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:
- perform arithmetic operations using MATLAB commands and call MATLAB functions;
- define variables of different types, form mathematical expressions using variables and change variable types;
- Print formatted output combining text and numbers.
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.
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
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 = 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)
(ii) 
(iii) 
(iv) 
(v) 
(vi)
(
means the remainder when x is divided by y) 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. Omitting the brackets from this command results in the command below. Enter this into the code cell below and run the live script.
This has calculated the value of
. Exercise 1 - Basic arithmetic operations
1. Use MATLAB commands to evaluate:
(a)
; (b)
; (c)
; 2 * (2 - 2 * (3 - 6 + 5 * (4 - 7)))
(d)
; 2 * (5 - 4 * (3 + 8)) / (3 * (4 - (3 - 5)))
(e)
; 2. Use a MATLAB command to calculate the remainder of 14151 divided by 571.
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:
- MATLAB assumes all angles are in radians
- The inverse functions for the other trigonometric ratios are calculated similarly.
Example 2
Evaluate the following:
(i) 
(ii) 
(iii) 
(iv) 
(v) 
(vi) 
Exercise 2 - Using mathematical functions
3. Use MATLAB commands to evaluate:
(a)
; (b)
; (c)
; (d)
; (e)
. 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
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.
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.
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:
- A variable name cannot start with a number and must start with a letter or the underscore character _.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9 and _).
- Variable names are case-sensitive (age, Age and AGE are three different variables).
Example 5
Enter the following command into the code cell below and run the live script (MATLAB will return an error, don't worry).
To overcome this we need to use a different variable name, e.g.,
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 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.
Types of variables
MATLAB uses the following types of variables:
- integers - whole numbers, e.g., 1, 10, -20.
- floating point numbers - real numbers expressed using an integer part and fractional part separated by a decimal point, e.g., 1.6, 3.1416.
- floating point exponential numbers - numbers expressed in standard form, e.g., 2e4 has the value
. - complex numbers - numbers of the form a+bi where a and b are real numbers and i is the imaginary number, e.g., 2+3i. Complex numbers are not common in programming and best avoided by treating their real and imaginary parts separately.
- Booleans - values which are either true or false.
- strings - sequences of letters, spaces and symbols, e.g., hello world.
When defining a variable MATLAB will automatically use the appropriate variable type depending on the value assigned.
Example 8
Define the following variables:
(i) 
(ii) 
(iii) 
(iv) 
(v) 
(vi) 
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
? 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.
hyp = sqrt(side1 ^ 2 + side2 ^ 2)
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.
angle = atan(opp / adj) * 180 / pi
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.
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.
Enter it into the code cell below and run the live script.
% This program calculates the sum
% calculate the sum of the two numbers
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.
Enter it into the code cell below and run the live script.
% The code below has been split over two lines (rather uneccessarily)
Printing output
To output text or the value of a variable within a MATLAB program we can use the fprintf command (help page). Example 12
The code below outputs 'hello world'.
Enter it into the code cell below and run the live script
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
The <format specifier> in the code above is one of the following
- %ai - outputs an integer number using a character spaces
- %a.bf - outputs a floating point number using a character spaces (including the decimal point) using b decimal places
- %a.be - outputs an exponential number using a character spaces (including the decimal point) using b decimal places
- %as - outputs a character string using a character spaces
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))
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)
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)
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. 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.
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.
Example 15
The command below uses an fprintf command to output an array of character strings.
Enter it into the code cell below and run the live script.
fprintf([ 'some 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))
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.
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;
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);
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.
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);
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.
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