Disclaimer: This article series recommends the use of Matlab. If you do not have access to Matlab, then I would recommend using Octave which is an open source alternative with almost completely similar syntax. You may use this online version https://octave-online.net.

Contents

1- Mathematical Models and Computers

2- Matlab Basics

1- Mathematical Models and Computers

Look at the world around you. You can make sense of many aspects of it. Take it a little further, you can predict a fairly good amount of it. For instance, grey clouds cover the sky — you automatically make the prediction that it will rain. That is an example of a very simply model. The input was visual data, the processing was the validation of the condition that there are grey clouds in the sky, and the output was a prediction that there will be rain. This model is a qualitative one. To make it of more use we quantify it.

You might enjoy this short story on the importance of quantitative descriptions — as a starting point of an agreement:

We will call upon a definition of quantitative models from this article,

What is a quantitative model?

It’s a theoretical and formal description of a system or a process that has been translated into the language of mathematics. Eykhoff defined it beautifully as ‘a representation of the essential aspects of an existing system (or a system to be constructed) which presents knowledge of that system in usable form’. Focus on the phrase ‘usable form’, it’ll come up later on.

Realizing that in order to quantify our model we use mathematics. The structure of a simple mathematical model is as follows:

Dependent var. = ƒ( Independent var., Parameters, Forcing Functions)

Lets break it down:

  • Dependent variable: is a quantity that reflects the behavior or state of a system
  • Independent variable: usually represents dimensions eg. space, time,.. — and are a quantities that are manipulated directly
  • Parameters: a set of constants that defines a system or sets the conditions of its operation
  • Forcing functions: external influences acting on a system

Analytical vs Numerical Solutions

Once we construct a mathematical model, naturally we seek to use it. We already possess a “usable form” of the system. To use it we input data into the model, process it (perform calculations), and the provide an output — which in this case is possibly the dependent variable. The beauty of a mathematical model is the ability for a person in Kuwait, the UK, or South Korea; to use it with different inputs and receive a different yet determinable output.

The problem we have however is with the processing stage where we perform calculations. There are two ways to solve a mathematical model:

  • Analytically: an analytical solution is a closed-form solution that exactly satisfies the models main equation
  • Numerically: a numerical solution is one given in terms of an approximation of a solution to the models main equation

The reason why we may opt to numerically solve a mathematical model is the fact that not all of them can be solved analytically. This is where numerical methods come in handy.

Numerical Methods

What are numerical methods? They are techniques by which mathematical problems are formulated so that they may be solved with arithmetic and logical operators.

Once we’ve managed to utilize a numerical method to solve our mathematical model numerically — we ought to compute our solution/calculation in one of two ways:

  • By hand
  • Using a computer

Of course we will select the most efficient way — using a computer. To do so, we must choose a programming language to write our model. A useful numerical programming language is Matlab because it is uniquely created to model such problems. Thus we will be using it throughout this article.

Unfortunately a computational price must be paid for a more accurate numerical solution (we will return to this in the coming parts). Hence, there is a trade off between accuracy and computational effort.

Examples of numerical methods:

  • Roots and optimization
  • Linear algebraic equations
  • Curve fitting
  • Integration and differentiation
  • Differential equations

2- Matlab Basics

In this section we will breeze through the fundamentals of Matlab, so as to have a functional use of it as a programming language.

The Matlab environment

It is broken down into four parts:

  • Command window = for direct code input
  • Graphics window = for graphs
  • Edit window = for scripting
  • Workspace = to see stored variables
From left to right: command window, graphics window, edit window, and workspace

How does assignment work?

Suppose we wanted to create the variable x and assign it a value of 6, we’d type this,

>> x = 6
x =
6

Matlab echo prints your commands. To suppress it we attach a semicolon at the end of the line,

>> x = 6;

Matlab is case sensitive, so x≠X.

Complex values are represented as i or j,

>> x = 1 + 5*i
x =
1.0000 + 5.0000i

Matlab also has a list of predefined values such as π,

>> pi
ans =
3.1416

So far what we’ve talked about was how scalar values are represented — how about vectors and matrices?

In Matlab, vectors and matrices are represented as arrays.

A one dimensional array is a vector. Whilst a two or more dimensional array is a matrix. Technically a scalar value is a one by one matrix, so it too is an array.

A row vector is assigned as such,

>> x = [1 2 3 4 5]
x =
1     2     3     4     5

On the other hand a column vector can be represented in this way,

>> x = [ 1; 2; 3; 4; 5]
x =
     1
     2
     3
     4
     5

or alternatively we could transpose a row vector by using an apostrophe,

>> x = [1 2 3 4 5]'
x =
     1
     2
     3
     4
     5

Constructing a matrix is intuitive. We can concatenate vectors together,

>> x = [[1 2 3]; [4 5 6]; [7 8 9]]
x =
     1     2     3
     4     5     6
     7     8     9

Suppose a, b, and c are row vectors, we could so this instead,

>> a = [1 2 3]; b = [4 5 6]; c = [7 8 9];
>> x = [a; b; c]
x =
     1     2     3
     4     5     6
     7     8     9

An important thing to keep in mind is that at times we would like to have control over the precision of our calculations. This means that we would like to specify the significant figures, scientific notation, decimal places etc.

>> format short
>> pi
ans =
3.1416
>> format long
>> pi
ans =
3.141592653589793
>> format bank
>> pi
ans =
3.14
>> format long e
>> pi
ans =
3.141592653589793e+00
>> format short e
>> pi
ans =
3.1416e+00
>> format short g
>> pi
ans =
3.1416
>> format long g
>> pi
ans =
3.14159265358979
>> format long eng
>> pi
ans =
3.14159265358979e+000
>> format short eng
>> pi
ans =
3.1416e+000

For more precision types, type in,

help format

‘help’ is a very useful command that we will be using in the coming sections when we deal with functions.

Vectors, Matrices, and Arrays

Calling a scalar variable is simple — just type in the variables name,

>> x
x =
6

Calling a vector is done in the same way. However what we care about the most is how do we call on specific elements in vectors and matrices?

The syntax is as follows:

  • a column vector a with m rows (so m elements) and we want to call the ith element: a(i)
  • a row vector with b with n columns (so n elements) and we want to call the ith element: b(i)
  • a matrix M with m rows and n columns (so mxn elements) and we want to call the element in the ith row and jth column: M(i,j)

Suppose we have the column vector a, row vector b, and matrix M,

>> a
a =
1     2     3     4     5
>> b
b =
6
     7
     8
     9
    10
>> M
M =
     1     2     3     4     5
     6     7     8     9    10
    11    12    13    14    15
    16    17    18    19    20
    21    22    23    24    25
>> a(3)
ans =
3
>> b(end)
ans =
10
>> M(2,5)
ans =
10

There are two useful in-built functions to create: a zero matrix and a matrix of ones,

>> zeros(2,4)
ans =
0     0     0     0
     0     0     0     0
>> ones(4,2)
ans =
1     1
     1     1
     1     1
     1     1

We know how to create arrays, how to call on elements within them — now how about manipulating them?

Simple. Matlab provides us with a nifty tool called the colon operator. It can be used to both create and manipulate arrays.

The syntax is as follows:

  • from : to → from a number to a number at an increment of one
  • from : increment : to → from a number to a number at a specified increment. If it from<to then increment is positive. If from>to then increment is negative.
  • A(m,:) → selects a whole row
  • A(:,n) → selects a whole column
  • t(nsmall,nbig) → selects from elements from nsmall to elements from nbig — inclusive.

Is there a more efficient way to create vectors of spaced points?

Fortunately there is. It’s called the linspace and logspace functions.

Linspace creates a row vector of equally spaced points, whilst logspace creates a row vector that is logarithmically equally spaced.

The syntax:

  • Linspace→ linspace(x₁,x₂,n)→ where x₁ is from, x₂ is to, n is number of points generated. If n is not specified then n=100.
  • Logspace→logspace(x₁,x₂,n)→ where x₁ is from, x₂ is to, n is number of points generated. If n is not specified then n=50.
>> linspace(1,4,8)
ans =
1.0000    1.4286    1.8571    2.2857    2.7143    3.1429    3.5714    4.0000
>> logspace(1,4,8)
ans =
1.0e+04 *
0.0010    0.0027    0.0072    0.0193    0.0518    0.1389    0.3728    1.0000

Character Strings

What are strings? They are alphanumeric — a sequence of characters. They too can be assigned:

>> string = 'enjoying this article?'
string =
'enjoying this article?'

What is encapsulated between the apostrophes is the string. Interestingly enough, individual strings can be concatenated by making a vector with each of these strings as an element within it.

There are many in-built functions regarding strings — however we will focus on one specific one that’ll come of use very soon. This function is called the disp function.

Syntax: disp(sprintf(‘string \nstring’))

The \n is essentially a command code that tells Matlab to print the next strings on a new line. It is important to note that Maltab interprets code left to right — this will be evident in the next section.

>> disp(sprintf('string \nstring'))
string 
string
>> disp(sprintf('string \n string'))
string 
 string

Mathematical Operations

Below is a list of the operations and their representation in Matlab:

  • Exponentiation: ^
  • Negation: –
  • Division: /
  • Left division (applies to matrix algebra): \
  • Addition: +
  • Subtraction: –

Within each precedence level, operators have equal precedence and are evaluated from left to right. Of course priority order can be overrides with parentheses — the same way a normal hand calculator works.

These operations are quite straightforwardly applied to scalars. However for arrays there are a few rules and particular ways to use these operations.

For example, the inner product of two vectors x and y is,

>> x
x =
45    23    17    34
>> y
y =
    50
    40
     1
    12
>> x*y
ans =
3595

The outer product on the other hand is,

>> y*x
ans =
        2250        1150         850        1700
        1800         920         680        1360
          45          23          17          34
         540         276         204         408

Both of them are dot products.

The same rules from linear algebra apply here — matrices cannot be multiplied is their dimensions are not equal.

Mixed operations whereby we multiply a scalar and a matrix are possible too.

Can we square each element in x?

>> x.^2
ans =
2025         529         289        1156

Yes we can! Notice the dot before the exponentiation operation? It is important to always place this dot before every operator to that element by element operation may take place.

Built-in Functions

Recall in the past few sections how we came across a multitude of built-in functions. What these functions essentially provide us with is the ability to not re-invent the wheel, hence saving time.

Let us focus our vision now on built-in functions that can be used on arrays. Basically all these functions act directly on a vector or matrix (automatically are element by element) unlike the mathematical operators we’ve seen.

Here are some notable mathematical functions — represented in their Matlab syntax:

  • log → natural log
  • sqrtm → square root in a matrix function
  • sqrt → square root
  • abs → absolute value
  • sin → sine
  • tanh → hyperbolic tangent
  • exp → exponential
>> sqrt(x)
ans =
6.7082    4.7958    4.1231    5.8310
>> sin(x)
ans =
0.8509   -0.8462   -0.9614    0.5291

There are other useful functions that allow us to ascertain certain pieces of information from an array or simply to manipulate them in a certain way. They are as follows:

  • round → rounds elements to the nearest integer
  • ceil → rounds elements to the nearest integer towards infinity
  • floor → rounds elements to the nearest integer towards minus infinity
  • sum → returns the summation of all the elements
  • min → finds the smallest element
  • max → finds the largest element
  • mean → finds the average of all the elements
  • prod → finds the product of all the elements
  • sort → sorts the elements in ascending order
  • length → finds the number of elements in an array
>> sum(x)
ans =
119
>> prod(x)
ans =
598230
>> max(x)
ans =
45
>> mean(x)
ans =
29.7500
>> sort(x)
ans =
17    23    34    45

One of the most important ways to visualize data is graphically. Matlab also allows us to do that with the use of the following in-built functions:

  • plot(x,y) → plots a graph with x on the x-axis and y on the y-axis
  • title(‘plot of y versus x’) → puts the title on the graph
  • xlabel(‘Values of x’) → puts the title of the x-axis
  • y-label(‘Values of y’) → puts the title of the y-axis
  • grid → puts grid
  • hold on → tells Matlab that the next commands must operate on the current graph plot and not on any other
  • hold off → terminates the hold on
  • axis square → makes the axes on a graph square

Suppose we wanted to further customize the graph, then we use what are called specifiers. Specifiers are typically placed within:

plot(x,y, list of specifiers separated by commas)

Below is a list of commonly used specifiers:

  • ‘MarkerSize’ → size of marker/point (default size is 6)
  • ‘MarkerEdgeColor’ and ‘MarkerFaceColor’→ are the interior colors (default is blue edge color and no face color)
  • ‘LineWidth’ → specifies line width (default is 1)

Each time we incur the command plot we create a new plot on a new window. What if for instance we wanted to create plots all on one window? Easy. We use → subplot(m,n,p). This creates a a graph within a window with dimension m by n and selects the p plot as the current plot.

How about three dimensional graphs? Not a problem. Use the function plot3(x,y,z) where x,y, and z are vectors of the same length.

To show how we can use the graphic functions, we’ll combine all of what we’ve learnt so far into one example.

The Example

We wanted to create three graphs in one window. The first is x vs t, the second is y vs t, and the third is a 3D plot of x, y, and z. In this example, t is from 0 to 2π with 200 points in between, x is cos(6t), y is sin(6t), and z is t. Make the line of the the first two graphs red and the last graph blue.

The example coded in the command window.
The three plots in one window.