Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

1

Introduction to matlab and revision on functions

1.1 Revision of programming from foundation

During foundation, the module fat0015 Fundamentals of programming I


covered the basics of programming. This was done using the programming lan-
guage, Pascal. The programming environment that was used was dev-Pasca�.
This software introduced the concept of a code editor where one writes the
code and a command window which prints output from the code and can also
read user input.
The course started off by introducing the basics of computers that included
details such as the concept of hardware and software, computer organization
and crucially, how data is represented using the binary number system. This
was followed by pseudocode, program design and flow charts. While these will
not be strictly imposed in this course, they maybe useful when one works with
programming problems.
After this initial introduction, the following important programming con-
cepts1 were demonstrated using Pascal: 1
Admittedly, there were more topics covered.
The topics highlighted here are the most im-
1. The concept of a variable was introduced and the different types of vari- portant ones for this course.

ables was also introduced. These types included real, double, string, boolean,
character and string. These were typically declared as

1 var
2 radius : rea�;
3 name : string;
4 �oopvar : integer;

2. Arithmetic expressions which are the same as that one gets in a calculator
were introduced along with built–in functions such as cos(). Also, the
concept of logical operators to determine the truth values of statements
were introduced. For example, executing the following Pascal fragment

1 (5 > 6) AND (2 <= 3)

would output FALSE because although the second expression in braces is


true (2 is less than 3), the first expression in braces is FALSE (5 is not greater
8 veb1062 computational methods for engineers

than 6) and the AND operator evaluates to true only if both expressions
evaluate to true.

3. The logical operators were then put to good use to write if statements for
decision making. For example, to print out a set of messages based on a
student’s score the following set of lines were used

1 var
2 score : rea�;
3

4 begin
5

6 score := 30;
7

8 if score >= 80 then


9 write�n(�Congratu�ations! Distinction!�)
10 e�se if score >= 40 then
11 write�n(�You have passed�)
12 e�se
13 write�n(�You have fai�ed. P�ease see me!�)
14

15 end.

4. A number of looping constructs were introduced ( for loops, whi�e loops


and unti� loops) for repeating instructions. For example, to print all the
numbers from 1 to 10 in Pascal, the following code may be used

1 var
2 i : integer;
3

4 begin
5

6 for i := 1 to 10 do
7 write�n(i);
8

9 end.

5. For storing a large number of elements of the same type, arrays were intro-
duced. For example, to print the first 10 entries in the multiplication table
for the number 5, the following Pascal code maybe used

1 var
2 i : integer;
introduction to matlab and revision on functions 9

3 five_times : array [1 .. 10] of rea�


4

5 begin
6

7 // Fi�� the array with the first 10 mu�tip�es


8 for i := 1 to 10 do
9 five_times[i] = 5*i;
10

11 // Print the array


12 for i := 1 to 10 do
13 write�n(five_times[i]);
14

15 end.

6. How to build user defined Procedures and functions that act just like
built–in functions were also introduced. A simple Procedure to print the
three input string arguments and how to call the procedure are demon-
strated below

1 Procedure Print3Names(n1, n2, n3 : string)


2 begin
3 write�n(�Some of the favourite characters�);
4 write�n(�of your �ecture is:�);
5 write�n(�Names: �, n1 + � � + n2 + � � + n3);
6 end
7

8 begin
9 Print3Names(�Kha�eesi�, �Wa�t�, �Frank�);
10 end.

Although not repeated here, the syntax for obtaining input from users were
also covered. Formatting the output of various variables such as rea� to ensure
certain number of decimal places were also covered. Another important omis-
sion in this quick revision is the interface to the file system. More specifically,
reading inputs and writing outputs from files has been omitted. Although these
topics haven’t been revised here, please ensure that you are familiar with the
basic concepts involved because even with matlab, they will become useful.

1.2 Basics of matlab

matlab is a high level2 programming environment that is ideal for most of the 2
This refers to the fact that you are at a higher
level from the bare metal hardware. The low
computing tasks one encounters as a practising engineer. As a beginner you
level workings of the computer is abstracted
away. The language you have learned be-
fore, Pascal, is low level because it gets com-
piled into machine instruction before it runs.
Never associate high level with better and low
level with worse.
10 veb1062 computational methods for engineers

may safely treat it as a glorified calculator where you can do more advanced
calculations and plot the results using fancy graphics3. 3
In fact, matlab started off as a simple pro-
gram that provides a simple interface to access
When one starts matlab, typically, it opens up two windows. One of them
the more complicated linear algebra programs
is called the command window and looks something like the picture shown available in the 1970’s. Prof Cleve Moler was
below. The most crucial components of this window are also labelled on the author of this simplified interface and he
developed them for his Linear Algebra stu-
dents from the mathematics department who
are not programmers. This became rather
popular in other universities across us. Fi-
nally, Prof Moler started off a spinoff com-
pany, MathWorks, and started selling this sim-
plified program under a commercial license.
That is a very brief introduction to the hum-
ble beginnings of matlab.

this figure. The largest part is taken up with a command prompt. This maybe
thought of as a more sophisticated version of the command prompt that you
saw in the dev-Pasca� software. To add two numbers, one just enters 1+2
in to the command prompt and press enter. That will print out the answer 3.
Multiplication, subtraction, division and other basic mathematical operations
are carried out in a similar manner. Now let’s say you want to evaluate the
expression c = a + b with a = 1 and b = 2. This is accomplished by
first typing a = 1 followed by b = 2 and then finally c = a + b. At the
end of this sequence of instructions, a third variable c would be produced
which would have a value of 3. Notice that unlike Pascal, there was no need
to declare the type of a, b and c in a var block. This is because matlab is a
dynamic programming language. A typical screen shot at the end this series
of commands is provided below. After running the series of commands,
notice the Workspace tab. It contains four variables, a, b, c as expected. It
also contains a variable ans, which corresponds to the answer obtained with
the evaluation of the last command. The workspace contains all the variables
that have been introduced in a given session. They can be removed from the
workspace by executing c�ear varname. For example c�ear a will remove
a from the workspace.
In a conceptually identical manner to what was done in Pascal, numbers
can be collected into an array in matlab too. However, in matlab–speak,
this is known as a vector. A vector v containing the numbers from 1 to 8
may be defined in a number of ways in matlab:
introduction to matlab and revision on functions 11

1 v = [1,2,3,4,5,6,7,8];
2 v = 1:1:8;

Both definitions produce the same output. Notice the semi–colon placed at the
end of each line. This will suppress the output from running the command.
The first method of defining v must look familiar from programming in Pascal.
Looking at the second method, the general form is actually start:space:end,
where space determines the difference between the elements, start is the first
number in the sequence and end is the last number in the sequence. All three
numbers in such a definition can be arbitrary. Once the vector is defined, the
elements can be obtained by indexing. In matlab the first element in a vector
has an index 1 and can be indexed as v(1). Notice that unlike Pascal, which
uses square braces, in matlab indexing is carried out with normal braces. To
obtain the third element in v, the required syntax is v(3). Indexing can also
be used to change a given element of an array. For example, the fourth element
of v can be changed from 4 to 4.8 by

1 >> v(4) = 4.8


2

3 v =
4

5 1.0 2.0 3.0 4.8 5.0 6.0 7.0 8.0

Given matlab’s use as a scientific computing tool, vectors are ubiquitous in


matlab. Therefore, there are more built–in functions that create vectors. Of
these, one of the most useful is �inspace. For example, to create a vector
containing 100 numbers between 1 and 10 (inclusive), the syntax is
12 veb1062 computational methods for engineers

1 x = �inspace(1, 10, 100);

Before moving ahead to do some interesting things with the vector x, it should
be pointed out that matlab comes with comprehensive documentation and
help. For example typing he�p �inspace produces

1 >> he�p �inspace


2 �inspace Linear�y spaced vector.
3 �inspace(X1, X2) generates a row vector of 100 �inear�y
4 equa��y spaced points between X1 and X2.
5

6 �inspace(X1, X2, N) generates N points between X1 and X2.


7 For N = 1, �inspace returns X2.
8

9 C�ass support for inputs X1,X2:


10 f�oat: doub�e, sing�e
11

12 See a�so �ogspace, co�on.

Notice that if �inspace is called with two arguments, it creates equally spaced
100 elements with the first argument as the starting point and the second
argument as the end point.
In addition to built–in array creation function, matlab also contains all
the usual mathematical functions. All the trigonometric functions (including
inverse ones) are readily available as built–in functions. The input argument
for these functions are in radians (for the inverse functions, return the angles
in radians)4. In addition to scalar (a single number), these functions also accept 4
Versions of these functions that take the an-
gle in degree are also available. However, for
vectors. In the case of a vector, the functions return a vector which contains
your own sanity, please stick to the versions
the function values at each of the elements in the input vector. For example, if that deal with radians
x = [0,1,3,4], y = cos(x), the vectors end up as Defining the vector

x= 0 1 2 3 4
y= cos(0) cos(1) cos(2) cos(3) cos(4)

x = �inspace(0, 4*pi, 100), evaluating the trigonometric functions


over this range should produce two cycles of the function because the period
of the trigonometric function is 2π 5. Evaluating y = cos(x) will produce 5
As you learned in Engineering Mechanics,
any function that keeps on repeating is called
the y values corresponding to the 100 equally distributed points in the range
cyclical and the x range over which it repeats
0 ≤ x ≤ 4π . In matlab, the produced (x, y) value pairs can readily be plotted corresponds to the period of the function
on a graph using the p�ot() function6. Evaluating sin and cos for the vector x 6
It is highly recommended that you read up
on the output of he�p p�ot. Many options
and plotting the results is accomplished as
for customizing matlab plots to look exactly
the way you want are provided in the docu-
mentation
1 x = �inspace(0, 4*pi, 100);
2 y1 = sin(x);
introduction to matlab and revision on functions 13

3 y2 = cos(x);
4

5 p�ot(x,y1,�b-�, x,y2,�r--�)

producing Now dissecting the p�ot function, it is seen that the two lines

0.5

0
2 4 6 8 10 12

−0 . 5

−1

are plotted with a single call to the p�ot function. Looking further, each
line is plotted with the (x,y) data followed by formatting information for the
resulting line. For the sin function, a blue line is specified with the ’b’ followed
by ’-’ indicating that a continuous line is required. Similarly, for cos, a red
( ’r’ ) dashed ( ’--’ ) line is specified. The collection of characters enclosed in
single quotes (‘’) is known as a string7. In matlab, strings are considered as a 7
Compare this with the double quotes (“”)
required in Pascal
vector of of characters. All the indexing rules apply to strings as well.
Exponential function is another important function that has applications
in many areas of civil engineering8. This function is also available in matlab 8
Very specifically, you will encounter this
in wastewater and environmental engineer-
using the command exp(). A typical call over −1 ≤ x ≤ 1 and the resulting
ing when microbial population growth/death
figure is in human waste is studied. The solution to
the differential equation solving the microbial
population growth is the exponential function
1 x = �inspace(-1, 1, 100);
2 y = exp(x);
3

4 p�ot(x,y)

producing Notice that this time around, the argument to the plot function
is only the x and y vectors. The line style is omitted and matlab is allowed
to choose the default line style.
An important point about general functions that was taught in Foundation
(or stpm) is that any function, f (x) can be expressed as the sum of an odd and
an even9 function. The even part, f e (x), in such a decomposition is given by 9
odd functions are functions for which
f (−x) = − f (x) and even functions are those
f (x) + f (−x) for which f (−x) = f (x)
f e (x) = ,
2
14 veb1062 computational methods for engineers

Figure 1.1: Exponential function, y = exp(x).

2.5

1.5

0.5

−1 −0 . 5 0 0.5 1

and the odd part, f o (x), is given by


f (x) − f (−x)
f o (x) = .
2
For exponential functions, the odd and even parts resulting from such a de-
composition are significant enough to have an own name, hyperbolic functions
and also appear in many civil engineering applications10. In fact, one of the 10
It appears in the solution to water waves and
cables hanging under its own weight
first appearance of these functions was in the solution to the so–called catenary
problem. This problem seeks a solution to the shape of an inextensible cable
hanging under its own weight. A typical example of this would be electrical
cables hanging between electric towers. The even part, denoted as cosh, is
defined as
exp(x) + exp(−x)
cosh = ,
2
A typical matlab fragment to generate cosh(x) over −1 ≤ x ≤ 1 and p�ot it
is provided below.

1 x = �inspace(-1, 1, 100);
2 y1 = cosh(x);
3 y2 = 0.5*exp(x);
4 y3 = 0.5*exp(-x);
5

6 p�ot(x,y1,x,y2,�--�,x,y3,�--�)

Notice that the y2 = 0.5 exp(x) and y3 = 0.5 exp(−x) are also plotted with
dashed lines on this figure. The odd part of the odd–even decomposition of
the exponential function, denoted as sinh(x) is defined as
exp(x) − exp(−x)
sinh = ,
2
A typical matlab fragment to generate the graph of this function over −1 ≤
x ≤ 1 along with the resulting plot is provided below.
introduction to matlab and revision on functions 15

Figure 1.2: y = cosh(x) along with the even


and odd components marked in grey
1.5

0.5

−1 −0 . 5 0 0.5 1

1.5
1 x = �inspace(-1, 1, 100);
2 y1 = sinh(x);
3 y2 = 0.5*exp(x); 1

4 y3 = -0.5*exp(-x);
5
0.5
6 p�ot(x,y1,x,y2,�--�,x,y3,�--�)

When it comes to functions, polynomials remain the first thing that proba- −1 −0 . 5 0.5 1
bly comes to mind. Some polynomial functions that you may have encountered
include −0 . 5

y1 = a 1 x + a 2
y2 = a 1 x 2 + a 2 x + a 3 −1
3 2
y3 = a 1 x + a 2 x + a 3 x + a 4

The first of these represent a straight line (constant slope), the second equation −1 . 5
represents a parabola (single turning point) and the third represents a cubic
polynomial. A typical matlab fragment to generate these three polynomials Figure 1.3: y = sinh(x) along with the even
and the plot resulting from this is provided below. and odd components marked in grey

1 a1 = 1;
2 a2 = 0.1;
3 a3 = -0.5;
4 a4 = 0.5;
5

6 x = �inspace(-1, 1, 100);
7 y1 = a1*x + a2;
8 y2 = a1*x.^2 + a2*x + a3;
16 veb1062 computational methods for engineers

y3 = a1*x.^3 + a2*x.^2 + a3*x + a4; 1


9 y1 (x)
10
y3 (x)
11 p�ot(x,y1,x,y2,x,y3)

In the matlab code, notice the ’ˆ’ operator. This operator represents raising −1 1
y2 (x)
a number to a certain power. For example, for y2, x.2̂ raises x to the power
of 2. Now focussing on the ’.’, this character means that x is a vector and
you require all the elements of this vector raised to the power of 2. In a similar
−1
manner, if you want to multiply all the members of vector x by itself, one
writes x.*x (again notice the ’.’). We will re–visit polynomials in §4.
Figure 1.4: Polynomials of various orders
By now, it can be noticed from the polynomial code that a bit of typing
is required. If one enters all of this in the command window, any mistake
would require moving back and re–typing everything from the point where
the mistake is made. This is where the second window that comes up when
matlab is started becomes useful. A typical view of this second window looks
like the screenshot below. After running the series of commands,notice

that Workspace This is called the matlab editor and you may find similarities
with the dev–Pascal editor that you have worked with before. Instead of typing
up the commands in the command window you can enter all the commands
you require into the matlab text editor, save it as a .m script file. This file can
then be run as many times you like by pressing Run. When you Run a script
file, the output from the script gets printed on the command window. Also, all
the variables produced from the run appear in the variable tab. The following
code provides a collection of all the matlab code that has been presented so
far in this chapter.

1 % Wipe the workspace, c�ose a�� windows and c�ear the command window
2 c�ear; c�ose a��; c�c;
3
introduction to matlab and revision on functions 17

4 %% Trigonometric functions
5

6 x = �inspace(0, 4*pi, 100);


7 y1 = sin(x);
8 y2 = cos(x);
9

10 figure(1)
11 p�ot(x,y1,�b-�, x,y2,�r--�)
12

13

14 %% Exponentia� function
15

16 x = �inspace(-1, 1, 100);
17 y = exp(x);
18

19 figure(2)
20 p�ot(x,y)
21

22

23 %% Hyperbo�ic functions
24 x = �inspace(-1, 1, 100);
25 y1 = cosh(x);
26 y2 = 0.5*exp(x);
27 y3 = 0.5*exp(-x);
28

29 figure(3)
30 p�ot(x,y1,x,y2,�--�,x,y3,�--�)
31

32 y1 = sinh(x);
33 y2 = 0.5*exp(x);
34 y3 = -0.5*exp(-x);
35

36 figure(4)
37 p�ot(x,y1,x,y2,�--�,x,y3,�--�)
38

39

40 %% Po�ynomia�s
41

42 a1 = 1;
43 a2 = 0.1;
18 veb1062 computational methods for engineers

44 a3 = -0.5;
45 a4 = 0.5;
46

47 x = �inspace(-1, 1, 100);
48 y1 = a1*x + a2;
49 y2 = a1*x.^2 + a2*x + a3;
50 y3 = a1*x.^3 + a2*x.^2 + a3*x + a4;
51

52 figure(5)
53 p�ot(x,y1,x,y2,x,y3)

The first line clears any previous variables, closes all figure windows and wipes
clean the command window. This is explained with a line beginning with %.
In matlab scripts, everything after a % is treated as a comment. Before each
figure is plotted figure() command is called to ensure that the figure resulting
from the p�ot() command is on a separate window. In this case the figure()
command is called with the plot window number. It can take many other
arguments11. 11
Read it up using the help command

1.3 Control flow in matlab

So far what has been computed and plotted are simple in built–functions. In
situations where the function is more complicated, just like what has been
done in Pascal, looping is required. In a similar manner, if any computation
requires decision–making, such as deciding whether a number is even or odd,
some form of if-e�se statement needs to be executed.

1.3.1 Looping
In matlab, the structure of a for loop is

1 for �oopVar = some_vector


2 % do your super duper computing
3 end

First, the loop executes for each element of some_vector. During each iteration
of the loop, the variab�e �oopVar takes the value of the consecutive elements
of some_vector. For example, if some_vector = 1:4, the loop executes 4
times (4 elements in some_vector ) and the value of �oopVar becomes 1 in the
first loop iteration, 2 in the next followed by 3 and 4, when the loop ends. This
is demonstrated by running

1 some_vector = 1:4;
2 for �oopVar = some_vector
3 disp(�Current va�ue of �oopVar =:�)
introduction to matlab and revision on functions 19

4 disp(�oopVar)
5 end

giving the following output12 12


Here the in–built function disp() is used
to print what needs to be printed on to the
command window. Another useful function
1 Current va�ue of �oopVar =: is fprintf()

2 1
3

4 Current va�ue of �oopVar =:


5 2
6

7 Current va�ue of �oopVar =:


8 3
9

10 Current va�ue of �oopVar =:


11 4

Some of the earlier examples may be written using for loops as follows

1 % Wipe the workspace, c�ose a�� windows and c�ear the command window
2 c�ear; c�ose a��; c�c;
3

4 %% Trigonometric functions
5

6 x = �inspace(0, 4*pi, 100);


7 ind_arr = 1:�ength(x);
8

9 for i = ind_arr
10 y1(i) = sin(x(i));
11 y2(i) = cos(x(i));
12 end
13

14 figure(1)
15 p�ot(x,y1,�b-�, x,y2,�r--�)
16

17

18 %% Exponentia� function
19

20 x = �inspace(-1, 1, 100);
21 y = zeros(size(x));
22
20 veb1062 computational methods for engineers

23 for i = 1:�ength(x)
24 y(i) = exp(x(i));
25 end
26

27 figure(2)
28 p�ot(x,y)

In understanding the code used to generate the trigonometric functions, recall


that to index the first element of vector x, the syntax is x(1). To facilitate
this indexing, the first thing that has been done is to create the index array
ind_arr. This is the array that has been looped over in the for loop. For
creating this array, another matlab built–in function, �ength() is used. This
function provides the total number of elements in a vector. Once this vector
is created, looping over this array assigns the index of the elements in vector
x to the loop variable i. This is then used to index the arrays y1, y2 and x to
produce sin() and cos() of each element of x. Notice that y1 and y2 are not
declared before the loop and keeps on growing with each iteration of the loop.
For example, in matlab, the following will run as well13 13
It is left as an exercise to explain what comes
out when this is run. Hint: Use the variable
explorer.
1 a(100) = 1;

While this is valid and works, the recommended way of doing this would be to
first assign an array of the right size as is done with the exponential function.
The built–in zeros() function is used to create a vector of the same size
as the vector x. As one can guess, the size() function gives the size of
the vector x. After the vector y is pre–defined and initialized to 0, the
computation of exp() for each element of vector x continues in an identical
manner to how y1 and y2 are computed.

1.3.2 if-e�se if-e�se


Making decisions is an important part of programming. A trivial problem that
an fyp student bashed the student’s head on a wall about back in 2009 was
how to decide whether a given number is even. As we all know from primary
school days, an even number is a multiple of 2. A different way of saying it
would be that if one divides the number by 2, the reminder must be 0. A useful
function provided by programming languages is mod(a,b), which provides
the reminder for a/b. Calling this function, for a given number a with b = 2
will give the reminder. If this reminder is 0, the number a is even and else it is
odd. This can be implemented in matlab as

1 a = 3;
2 if (mod(a,2) == 0)
3 disp(�a was an even number�);
4 e�se
5 disp(�a was an odd number�);
introduction to matlab and revision on functions 21

6 end

In this example, a = 3 and in the first if statement, it is checked whether the


call to mod() function returns a 0. If this condition is true, it displays that it is
an even number and if this condition is false, it displays that the number is odd
(it can be either odd or even). A more generic version of an if block is

1 if condition1
2 % do something if condition1 is true
3 e�seif condition2
4 % do something if condition2 is true
5 e�seif condition3
6 % do something if condition2 is true
7 e�se
8 % None of the conditions were true, so do something
9 end

Using this generic if block, the block to detect whether a number is a multiple
of 1, 2, 3, or 4 is

1 a = 3;
2 if (mod(a, 2) == 0)
3 disp(�a was a mu�tip�e of 2�);
4 e�seif (mod(a, 3) == 0)
5 disp(�a was a mu�tip�e of 3�);
6 e�seif (mod(a, 4) == 0)
7 disp(�a was a mu�tip�e of 4�);
8 e�se
9 disp(�a was not a mu�tip�e of 2, 3 or 4�);
10 end
Condition Syntax
Looking at the conditions, so far what has been checked for is equality. We Equal to ’==’
can also check whether a number is not equal to, greater than or less than. A Not equal to ’ =’
Less than ’<’
summary of the syntax involved is provided in the table on the right. Less than or equal to ’<=’
These conditions can further be chained together. To check whether the Greater than ’>’
Greater than or equal to ’>=’
number a is a multiple of both 3 and 5 at the same time, the test for 3 and 5
Table 1.1: Summary of syntax used for logical
above can be chained together as conditions

1 a = 15;
2 if ( (mod(a, 2) == 0) && (mod(a, 3) == 0) )
3 disp(�a is a mu�tip�e of 2 AND 3�);
4 e�se
5 disp(�a is not a mu�tip�e of 2 AND 3�);
22 veb1062 computational methods for engineers

6 end

Here it is checked whether condition1 AND codition2 are true at the same
time. It can also be checked whether condition1 OR condition2 are true
using ’||’.
As a final example that puts together looping and if statements, consider
the following equation14 14
This is a simplified version of the function
that represents the distribution of energy in
� �
� � exp − (x−22)
2
the open ocean during a storm. Those of you
y(x) = x −5 · exp −20 x −4 · 2 8σ , who are interested, look up jonswap spec-
trum.
where


 0.07 x ≤ 2
σ= 
 0.09 x > 2

To plot y(x) over 0 ≤ x ≤ 4, one has to loop over all the x values and set the
value of σ based on the x value. This can be implemented as

1 % Define x and initia�ize y


2 x = �inspace(0, 4, 100);
3 y = zeros(size(x));
4

5 for i = 1:�ength(x)
6 % Choose sig based on x va�ue
7 if (x(i) >= 2)
8 sig = 0.07;
9 e�se
10 sig = 0.09;
11 end
12

13 % With the chosen sig va�ue, compute the y va�ue


14 % at the current x va�ue
15 y(i) = x(i).^(-5)* ...
16 exp(-20*x(i).^(-4))* ...
17 2^(exp(-(x(i)-2)^2/(8*sig^2)));
18 end
0 . 02
19

20 % P�ot the function


21 p�ot(x,y)
0 . 01

producing the figure on the right.

1.4 Vectorisation in matlab


0
1 2 3 4
When applying a function, f (x) to a vector x, it has been done in two ways;
applying it to each element of vector x or applying it to the whole vector. Figure 1.5: Figure produced for y(x) that con-
tains a condition
introduction to matlab and revision on functions 23

This second method is known as vectorisation in matlab lingua–franca.


This is not only applied when calling built–in functions such as cos(). It can
be combined with logical conditions as well to produce compact and efficient
code. To understand how this can work, one has to first understand mask
arrays. A mask array is an array that contains either 1 or 0 as its elements. If
the length of this array is the same as the length of a vector v, indexing v with
the mask array would output the elements of v whose index corresponds to a
1 in the mask array. For example, for the vector v , to obtain the elements
in the odd positions, the following matlab code may be used

1 v = [2,1,5,8];
2 indarr = [1,3];
3 vodd = v(indarr);

Using mask arrays, an identical effect may be produced by

1 v = [2,1,5,8];
2 maskarr = [true,fa�se,true,fa�se];
3 vodd = v(maskarr);
4

5 % This wi�� produce


6 % vodd =
7 % 2.00 5.00

The concept of mask arrays can be combined with logical conditions to produce
compact code. To obtain the values in a vector v greater than 4, logical
conditions and mask arrays maybe used as follows

1 v = 1:8;
2 maskarr = v > 2; % Logica� condition used to produce a mask array
3 vgt2 = v(maskarr);
4

5 % This wi�� produce


6 % vgt2 =
7 % 3.00 4.00 5.00 6.00 7.00 8.00

In this code, v > 2 will produce a vector with 1 in the places where v contains
elements with a value greater than 2 and 0 elsewhere. Indexing v with this
mask array outputs the elements of v greater than 2. Always remember the 2
stages involved in the use of masks.
This technique maybe used to write the earlier example with for loops
involving y(x) and σ as follows

1 % Define x and initia�ize y


2 x = �inspace(0, 4, 100);
24 veb1062 computational methods for engineers

3 y = zeros(size(x));
4

5 mask1 = x <= 2;
6 sig1 = 0.07;
7

8 mask2 = x > 2;
9 sig2 = 0.09;
10

11 y(mask1) = x(mask1).^(-5)* ...


12 exp(-20*x(mask1).^(-4))* ...
13 2^(exp(-(x(mask1)-2)^2/(8*sig1^2)));
14 y(mask2) = x(mask2).^(-5)* ...
15 exp(-20*x(mask2).^(-4))* ...
16 2^(exp(-(x(mask2)-2)^2/(8*sig2^2)));
17

18 % P�ot the function


19 p�ot(x,y)

It should be added that due to the interpreted nature of matlab, it is always


advisable to go for vectorisation instead of loops.

1.5 matlab functions

So far what has been used are built–in functions. Users can also define functions
that can be used in the same manner as built–in functions. The general form
for a user defined function is

1 function [output1, output2, ...] = fMyFunction(input1, input2, ...)


2 % do awesome computations
3 output1 = % something
4 output2 = % something e�se
5

6 end

The function is called fMyFunction and the matlab code must be saved in
a script file named fMyFunction.m. The inputs are listed after the function
name as input1, input2, .... Here ’...’ means that any other inputs
may be added, separated by ’,’. Similarly, outputs that the function produces
maybe written after the function keyword, enclosed in square braces, ’[]’.
Each output variable needs to be assigned inside the function.
The piece of matlab script used to check whether a number is even intro-
duced earlier can be wrapped in a function fIsEven() as follows
introduction to matlab and revision on functions 25

1 function iseven = fIsEven(x)


2

3 if (mod(x,2) == 0)
4 iseven = true;
5 e�se
6 iseven = fa�se;
7 end
8

9 end

The function takes a single input x and outputs a single variable, iseven. The
output variable is set to true if the number is even and fa�se if it is not even
(odd). true and fa�se are called boo�eans types which is used to determine
the truth of a statement. In matlab, truth or true is in reality the number 1
and fa�se is the number 0. Therefore, 1 and 0 maybe used interchangeably
with true or fa�se. This is exactly why the mask arrays used earlier contained
1 and 0; they are just true and fa�se. Once this function is defined, it maybe
used as follows

1 a = 15;
2 if (fIsEven(a))
3 disp(�a is even�);
4 e�se
5 disp(�a is odd�);
6 end

The earlier example involving for loop and if statement is a good example
to be written as a function. This is wrapped in the function fExamp�e2()
as follows

1 function y = fExamp�e2(x)
2 % initia�ize y
3 y = zeros(size(x));
4

5 mask1 = x <= 2;
6 sig1 = 0.07;
7

8 mask2 = x > 2;
9 sig2 = 0.09;
10

11 y(mask1) = x(mask1).^(-5)* ...


12 exp(-20*x(mask1).^(-4))* ...
26 veb1062 computational methods for engineers

13 2^(exp(-(x(mask1)-2)^2/(8*sig1^2)));
14 y(mask2) = x(mask2).^(-5)* ...
15 exp(-20*x(mask2).^(-4))* ...
16 2^(exp(-(x(mask2)-2)^2/(8*sig2^2)));
17 end

Once this function is defined, it may be used in a script as follows

1 x = �inspace(0, 4, 100);
2 y = fExamp�e2(x);
3 p�ot(x, y)

Notice that apart from being less cluttered, it also introduces only the variables
x and y to the workspace. This is because the other variables such as mask1
and sig1 are wiped clean when the function fExamp�e2 finishes execution.

1.6 Manipulation of functions

For a single variable function of the form y = f (x), understanding what


happens to the graph of the function when the axes are shifted and scaled is very
useful15. Starting with the y–axis, shifting just moves the graph up or down. 15
The relatively simple matlab code used for
generating the figures in this section are not
Taking the trigonometric functions as an example
included in the text. You are encouraged to
reproduce them yourself
y = sin(x)

adding a constant c shifts the whole graph up by the amount c

y = sin(x) + c

The figure below demonstrates what happens when c = 1 and c = −1 for


y = sin(x). Scaling of the form

y = c sin(x)

is similarly is similarly relatively simple for y–axis. An example of scaling with


c = 0.5 and c = 1.5 is provided below.
On the x–axis, a shift of the form

y = sin(x + c)

shifts the whole graph to the right when c < 0 and to the left when c > 0, as
demonstrated below. An important shift for trigonometric functions is
� π�
y = sin x + = cos(x).
2
Scaling for x –axis shrinks or expands the graphs. For a general scaling of the
form
y = f (cx),
if c > 1, the graph shrinks (more of the graph fits over the same interval)
and if c < 1, the graph expands (less of the graph fits over the same interval).
To demonstrate this, c = 0.5 and c = 2 is applied to y = exp(cx) over
−0.5 ≤ x ≤ 0.5 and to y = sin(cx) over 0 ≤ x ≤ 4π as shown below.
introduction to matlab and revision on functions 27

Figure 1.6: The effect of a shift of the form


Shifted up y = f (x) + c applied to sin(x)
2

1
sin(x) + 1

sin(x)
Shifted down
−1
sin(x) − 1

−2
0 1 2 3 4 5 6

Figure 1.7: The effect of scaling of the form


Stretched up y = c f (x) applied to sin(x)
2
sin(x)

1
0. 5 sin (x)
0

Squeezed down
−1

1. 5 sin (x)
−2

0 1 2 3 4 5 6
28 veb1062 computational methods for engineers

2 Figure 1.8: The effect of a shift of the form


y = f (x + c) applied to sin(x)
sin(x + 1)
Shifted right
1

sin(x − 1)

−1 Shifted left
sin(x)

−2
0 1 2 3 4 5 6

Figure 1.9: The effect of scaling of the form


y = f (c x) applied to sin(x)
Shrinked Expanded

1 sin(0. 5 x)

−1
sin(2 x) sin(x)

0 1 2 3 4 5 6

You might also like