Вы находитесь на странице: 1из 46

MATLAB primer ©

1
Lecture Notes: ML3L009

Kodanda Ram Mangipudi


School of Minerals, Metallurgical and Materials Engineering
Indian Institute of Technology Bhubaneswar

January 23, 2020

1
Disclaimer: This is a draft still under development, and is therefore incomplete,
may contain errors, typos, etc. Use with caution.
2
Contents

1 The MATLAB environment 5

1.1 Description of MATLAB GUI . . . . . . . . . . . . . . . . . . . . 5

2 Parts of a MATLAB script 7

2.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.2 Basic data types . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2.3 Vectors, Matrices, and Arrays . . . . . . . . . . . . . . . . . . . . 9

2.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2.5 Array Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2.6 Decision making . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.7 if constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2.8 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

2.9 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

2.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

2.11 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

2.12 Data import and export . . . . . . . . . . . . . . . . . . . . . . . 37

3 Basic Plotting 39

3.1 Line plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

3.2 Surface plots and contours . . . . . . . . . . . . . . . . . . . . . . 41

3
4 CONTENTS

3.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Chapter 1

The MATLAB environment

1.1 Description of MATLAB GUI

Different panes in the MATLAB GUI:

1. Command area: This is like a terminal in Linux or cmd in windows.


Displays all the commands that have been run so far and their terminal
output, if any.

2. Editor: This is the notepad-like window for creating and editing matlab
source files.

3. Directory browser/navigator

4. Workspace: This shows the currently loaded user variables and their values
in MATLAB memory space, called the workspace. Helpful for investigating
the structure of derived datatypes and their values.

Files: scripts and functions

1. Saving a script file

2. Opening a script file

3. Running a script file

5
6 CHAPTER 1. THE MATLAB ENVIRONMENT
Chapter 2

Parts of a MATLAB script

A script is a collection of statements that will be executed by MATLAB. Scripts


are used in interpreters like MATLAB and do not need a compilation and linking
steps. Statements are listed on separate lines, or as separated by semicolons if
present on the same line. A semicolon suppresses the output of the evaluation
of that statement.

List of useful commands who, whos, format, clear, clc, help, doc

2.1 Variables

A valid variable name should start with a letter and may be followed by letters,
digits, and underscores. MATLAB is case sensitive. A variable name cannot
start with a digit, and cannot contain special symbols such as the operators,
dot, colon, semicolon, &, etc. One may not use only the reserved keywords, for
example, end, for, etc.; however, these words may form part of a variable name,
anywhere in it: at the beginning, middle, or at the end.

Unlike in traditional languages, e.g., C or FORTRAN, there is no need to


define the variables before their use. Their first appearance in the script/function
automatically allocates memory to the variable to create it in the workspace.
This is while being a very convenient feature, it also warrants a careful coding
practice and keen eye as any typos in using a variable will create a new variable
if appears in assignment statements.

Check the functions: exists, iskeyword, isvarname, which, clear

7
8 CHAPTER 2. PARTS OF A MATLAB SCRIPT

2.1.1 Reserved function names or commands

Some names are reserved for intrinsic function names. It is therefore advisable
not to reuse in your code for other purposes.

min max sqrt dot cat find


length size sort zeros ones det
inv num2str str2num plot contour surf
axis axes grid figure hold legend
subplot load

2.2 Basic data types

2.2.1 Numeric types

int8 8-bit signed integer int32 32-bit signed integer


int16 16-bit signed integer int64 64-bit signed integer
uint8 8-bit signed integer uint16 16-bit signed integer
uint32 32-bit signed integer uint64 64-bit signed integer
single single precision numerical data doubel double precision numerical data

2.2.2 Complex numbers

Complex part numbers denoted with i, for example,


1 z =2.5+3 i ;

2.2.3 Boolean type

logical: logical values of 1 or 0, represent true and false respectively

2.2.4 Characters and strings

Single characters: e.g.


1 yes_or_no = ' y ' ;

Strings are defined/created as


1 str = ' Hello World ' ;
2.3. VECTORS, MATRICES, AND ARRAYS 9

The strings are stored as vector of characters.

2.2.5 Cell

Array of indexed cells, each capable of storing an array of a different dimension


and data type

2.2.6 Type conversion

ˆ double(n)
ˆ int8(x)
ˆ uint16(p)
ˆ int2str(x)
ˆ num2str(p)
ˆ ...

2.2.7 Type checking

Return value is logical.

ˆ isinteger(x)
ˆ isflaot(p)
ˆ ischar(a)
ˆ isreal(r)
ˆ isvector(amat)
ˆ isnumeric(abc)
ˆ isscalar(pressure)

2.3 Vectors, Matrices, and Arrays

2.3.1 Vectors

A vector is a one-dimensional array of numbers. MATLAB allows creating two


types of vectors: row and column vectors.
10 CHAPTER 2. PARTS OF A MATLAB SCRIPT

Row vectors are created by enclosing the set of elements in square brackets,
using space or comma to delimit the elements:
1 rvec = [1 2 3 4 5];

Column vectors are created by enclosing the set of elements in square brack-
ets, using semicolon to delimit the elements:
1 cvec = [6; 7; 8; 9; 10;];

2.3.2 Matrices

Create and initialize a matrix by:


1 mat = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8];

2.3.3 Array

Arrays have to the created by allocating space for a variable. For example, the
following creates an array a of size (M,N,P) and initializes all its elements to
zero.
1 a = zeros (M ,N , P ) ;

Other functions like ones(), eye(), rand() can also be used to create
matrices of different kinds.

2.3.4 Referencing elements

Elements of vectors, matrices, or arrays are referenced using round braces and
with the element index. For example, the second element of cvec is accessed as
cvec(2). Unlike C, the vector or array indices start from 1 rather than from 0.

The (i,j) th element is referenced by mat(i,j) for a matrix.

2.3.5 Vector manipulations

Create vectors with uniformly-spaced elements

1 >> steps =0:5:50


2
2.3. VECTORS, MATRICES, AND ARRAYS 11

3 steps =
4
5 0 5 10 15 20 25 30 35 40
45 50
6
7 >> x = -0.2:0.1:0.2
8
9 x =
10
11 -0.2000 -0.1000 0 0.1000 0.2000
12
13 >> a =1:3
14
15 a =
16
17 1 2 3

Length, number of elements, and array dimensions

1 x = [3.1 , 8.2 , 7.2 , 78/2 , 9.9 , 1.1];


2 length ( x ) % length of x vector
3
4
5 y = rand (3 , 4 , 5 , 2) ;
6 ndims ( y ) % no of dimensions in array y
7
8
9 animals = [ ' cat ' , ' dog ' , ' cow ' , ' pig ' ];
10 numel ( animals ) % no of elements in animals

Sorting

1 v = [ 23 45 12 9 5 0 19 17]; % horizontal vector


2 sort ( v ) ; % sorting v
3 m = [2 6 4; 5 3 9; 2 0 1]; % two dimensional array
4 sort (m , 1) ; % sorting m along the row
5 sort (m , 2) ; % sorting m along the
column
12 CHAPTER 2. PARTS OF A MATLAB SCRIPT

Slicing/range/subarrays

We can obtain/access subarrays (vectros, matrices, or arrays) using the colon


operator. For example,
1 >> v = [ 23 45 12 9 5 0 19 17]; % define a
vector
2 >> v (3:6)
3
4 ans =
5
6 12 9 5 0
7
8 >> subv = v (3:6) % elements from 3 rd to 6 th
9
10 subv =
11
12 12 9 5 0
13
14 >> v (1:3) =[100 101 102]; % overwrite some
elementsr
15 >> v
16
17 v =
18
19 100 101 102 9 5 0 19 17

Appending elements and vectors to vectors

1 >> v = [ 1 2 3 4 5 6 7]
2
3 v =
4
5 1 2 3 4 5 6 7
6
7 >> v ( end +1) =8 % assign an element at the end
of the vector
8
9 v =
10
11 1 2 3 4 5 6 7 8
12
13 >> v =[ v ,9]
14
15 v =
2.3. VECTORS, MATRICES, AND ARRAYS 13

16
17 1 2 3 4 5 6 7 8 9
18
19 >> v =[ v (1:3) ,100 , v (4: end ) ] % insert an element in
a vectror
20
21 v =
22
23 1 2 3 100 4 5 6 7 8
9
24
25 >> a =1:3
26
27 a =
28
29 1 2 3
30
31 >> b =5:8
32
33 b =
34
35 5 6 7 8
36
37 >> c =[ a ,4 , b ]
38
39 c =
40
41 1 2 3 4 5 6 7 8

Deleting elements

1 >> v
2 v =
3
4 1 2 3 100 4 5 6 7 8
9
5
6 >> v (1) =[]
7
8 v =
9
10 2 3 100 4 5 6 7 8 9
11
12 >> v (3:4) =[]
13
14 CHAPTER 2. PARTS OF A MATLAB SCRIPT

14 v =
15
16 2 3 5 6 7 8 9

2.3.6 Matrix/array manipulations

Access rows and columns

1 >> a =[1:4;5:8;9:12]
2
3 a =
4
5 1 2 3 4
6 5 6 7 8
7 9 10 11 12
8
9 >> a (: ,1) % first column
10
11 ans =
12
13 1
14 5
15 9
16
17 >> a (: ,2) % second column
18
19 ans =
20
21 2
22 6
23 10
24
25 >> a (: ,3) % third column
26
27 ans =
28
29 3
30 7
31 11
32
33 >> a (1 ,:) % first row
34
35 ans =
36
2.3. VECTORS, MATRICES, AND ARRAYS 15

37 1 2 3 4
38
39 >> a (3 ,2:4) % third row , elements 2 to 4
40
41 ans =
42
43 10 11 12

Deleting row or a column

Deleting a single element is illegal for an array or a matrix. However, entire


rows or columns can be deleted at once. On the other hand, overwriting a single
element or a portion of a row or column is allowed.
1 >> a
2
3 a =
4
5 1 2 3 4
6 5 6 7 8
7 9 10 11 12
8
9 >> a (1 ,:) =[] % delete first row
10
11 a =
12
13 5 6 7 8
14 9 10 11 12
15
16 >> a (: ,2) =[] % delete second column
17
18 a =
19
20 5 7 8
21 9 11 12

List of indices as arguments

1 >> a = round ( rand (4 ,4) *100 )


2
3 a =
4
5 90 34 78 10
16 CHAPTER 2. PARTS OF A MATLAB SCRIPT

6 94 90 39 13
7 49 37 24 94
8 49 11 40 96
9 >> b = a ([2 ,3] ,:) % create a matrix with 2 nd and 3 rd
rows
10
11 b =
12
13 94 90 39 13
14 49 37 24 94
15
16 >> c = a ([2 ,3] ,2: end ) % create a matrix with 2 nd and
3 rd rows
17
18 c =
19
20 90 39 13
21 37 24 94
22
23 >> ind = find ( a (: ,1) >50)
24
25 ind =
26
27 1
28 2
29
30 >> str = ' abcdabcdabcdabcd '
31
32 str =
33
34 abcdabcdabcdabcd
35
36 >> find ( str == ' a ' )
37
38 ans =
39
40 1 5 9 13
41
42 >> str_new = str ( find ( str ~= ' a ' ) )
43
44 str_new =
45
46 bcdbcdbcdbcd
47
48 >> str ( find ( str == ' a ' ) ) = ' x '
49
2.4. OPERATORS 17

50 str =
51
52 xbcdxbcdxbcdxbcd

2.4 Operators

1. Arithmetic operators: +, −, ∗, /,ˆ, \, 0 , and their vector/matrix versions

2. Relational operators: <, >, <=, >=, ==, ∼=

3. Logical operators: Element-wise logical operators operate element-by-element


on logical arrays. The symbols &, |, and ∼ are the logical array operators
AND, OR, and NOT.
Short-circuit logical operators allow short-circuiting on logical operations.
The symbols && and || are the logical short-circuit operators AND and
OR.

4. Bitwise operators

5. Set operators

2.5 Array Operations

Some important vector operations are:

2.5.1 Addition and Subtraction of vectors, matrices, arrays

1 >> a = rand (3 ,3)


2
3 a =
4
5 0.7317 0.5470 0.1890
6 0.6477 0.2963 0.6868
7 0.4509 0.7447 0.1835
8
9 >> b = rand (3 ,3)
10
11 b =
12
13 0.3685 0.0811 0.4868
14 0.6256 0.9294 0.4359
15 0.7802 0.7757 0.4468
18 CHAPTER 2. PARTS OF A MATLAB SCRIPT

16
17 >> c = a + b
18
19 c =
20
21 1.1002 0.6281 0.6757
22 1.2734 1.2257 1.1226
23 1.2312 1.5204 0.6303
24
25 >> d =a - b
26
27 d =
28
29 0.3632 0.4659 -0.2978
30 0.0221 -0.6331 0.2509
31 -0.3293 -0.0310 -0.2633

2.5.2 Scalar Multiplication

1 >> a = rand (3 ,3)


2
3 a =
4
5 0.3507 0.5502 0.2077
6 0.9390 0.6225 0.3012
7 0.8759 0.5870 0.4709
8
9 >> a *2
10
11 ans =
12
13 0.7015 1.1003 0.4155
14 1.8780 1.2450 0.6025
15 1.7519 1.1741 0.9418
16
17 >> 2* a
18
19 ans =
20
21 0.7015 1.1003 0.4155
22 1.8780 1.2450 0.6025
23 1.7519 1.1741 0.9418
24
25 >> x =0:0.2:1
26
2.5. ARRAY OPERATIONS 19

27 x =
28
29 0 0.2000 0.4000 0.6000 0.8000
1.0000
30
31 >> 3* x
32
33 ans =
34
35 0 0.6000 1.2000 1.8000 2.4000
3.0000
36
37 >> x *3
38
39 ans =
40
41 0 0.6000 1.2000 1.8000 2.4000
3.0000

2.5.3 Transpose of a Vector, Matrix (Array transpose is not


defined)

1 >> x
2
3 x =
4
5 0 0.2000 0.4000 0.6000 0.8000
1.0000
6
7 >> x '
8
9 ans =
10
11 0
12 0.2000
13 0.4000
14 0.6000
15 0.8000
16 1.0000
20 CHAPTER 2. PARTS OF A MATLAB SCRIPT

2.5.4 Vector Dot Product

The dot product is noting but sum of the element-by-element product of the two
vectors. There is also a dedicated function dot().
1 >> x .* x
2
3 ans =
4
5 0 0.0400 0.1600 0.3600 0.6400
1.0000
6
7 >> sum ( x .* x )
8
9 ans =
10
11 2.2000
12
13 >> dot (x , x )
14
15 ans =
16
17 2.2000

2.5.5 Element by element product of matrices

1 >> a
2
3 a =
4
5 0.3507 0.5502 0.2077
6 0.9390 0.6225 0.3012
7 0.8759 0.5870 0.4709
8
9 >> b
10
11 b =
12
13 0.3685 0.0811 0.4868
14 0.6256 0.9294 0.4359
15 0.7802 0.7757 0.4468
16
17 >> c = a * b
18
19 c =
2.5. ARRAY OPERATIONS 21

20
21 0.6355 0.7009 0.5033
22 0.9705 0.8884 0.8630
23 1.0575 0.9820 0.8927

2.5.6 Multiplication of matrices

1 >> a = rand (2 ,3)


2
3 a =
4
5 0.2305 0.1948 0.1707
6 0.8443 0.2259 0.2277
7
8 >> b = rand (3 ,2)
9
10 b =
11
12 0.4357 0.4302
13 0.3111 0.1848
14 0.9234 0.9049
15
16 >> c = a * b
17
18 c =
19
20 0.3186 0.2896
21 0.6484 0.6110

2.5.7 Element-wise multiplication of matrices

1 >> p = rand (3 ,3)


2
3 p =
4
5 0.9797 0.2581 0.2622
6 0.4389 0.4087 0.6028
7 0.1111 0.5949 0.7112
8
9 >> q = rand (3 ,3)
10
11 q =
12
22 CHAPTER 2. PARTS OF A MATLAB SCRIPT

13 0.2217 0.3188 0.0855


14 0.1174 0.4242 0.2625
15 0.2967 0.5079 0.8010
16
17 >> r = p .* q
18
19 r =
20
21 0.2173 0.0823 0.0224
22 0.0515 0.1734 0.1582
23 0.0330 0.3021 0.5697

2.5.8 Direct solution set of simultaneous equations

1 >> A = rand (3 ,3)


2 A =
3
4 0.424994 0.488325 0.845609
5 0.587216 0.691113 0.406523
6 0.091074 0.650774 0.929493
7
8 >> b = rand (3 ,1)
9 b =
10
11 0.162864
12 0.043910
13 0.878935
14
15 >> x = A \ b
16 x =
17
18 -1.50190
19 1.18482
20 0.26323

The result can be verified by finding the inverse of the quotient matrix:
1 >> x = inv ( A ) * b
2 x =
3
4 -1.50190
5 1.18482
6 0.26323
2.6. DECISION MAKING 23

2.6 Decision making

2.7 if constructs

2.7.1 if - end

1 a = rand (1 ,5) ;
2
3 if ( a (2) >2)
4 a (2) = a (2) +100;
5 end

2.7.2 if - else - end

1 if ( a (2) >0.5)
2 a (2) = a (2) +100;
3 else
4 a (2) = a (2) *2;
5 end

2.7.3 if - elseif - end ladder

1 if ( a (2) <0.5)
2 a (2) = a (2) +100;
3 elseif ( a (2) <0.8)
4 a (2) = a (2) +50;
5 elseif ( a (2) <0.9)
6 a (2) = a (2) *2;
7 end

2.7.4 Nested ifs

1 if ( a (2) <0.9)
2 if ( a (2) <0.8)
3 a (2) = a (2) +50;
4 elseif ( a (2) <0.5)
5 a (2) = a (2) *2;
6 end
7 else
8 a (2) =0.0;
24 CHAPTER 2. PARTS OF A MATLAB SCRIPT

9 end

2.8 Loops

2.8.1 while loop

1 a =15;
2 while ( a < 20 )
3 fprintf ( ' value of a : % d \ n ' , a ) ;
4 a = a + 1;
5 end

2.8.2 for loop

General syntax is:


1 for index = values
2 < program statements >
3 end

The values is a vector (row or column) of integer indices, not necessarily in


sequence!
1 for a = 10:20
2 fprintf ( ' value of a : % d \ n ' , a ) ;
3 end

The values vector can also be generated using standard vector generating com-
mand, like
1 for a = 1.0: -0.1: 0.0
2 disp ( a )
3 end

or
1 for a = [24 ,18 ,17 ,23 ,28]
2 disp ( a )
3 end
2.9. EXAMPLES 25

2.8.3 Nested loops

for and while can be nested any number of times and in any manner.

2.8.4 Loop control statements

break

Terminates the loop containing the break statement and transfers execution to
the statement immediately following the loop.

continue

Causes the loop to skip the remainder of its body and returns the control to the
beginning of the loop.

2.9 Examples
1. Rama bought three apples, a dozen bananas, and an orange for Rs. 236.
Sita bought a dozen apples and two oranges for Rs. 526. Krishna bought
two bananas and three oranges for Rs. 277. Find how much one piece of
each type of fruit cost.

Solution: With the prices of each kind of fruit unknown, the above prob-
lems leads to a set of three simultaneous linear equations. This can thus be
solved by building a matrix equation Ax = b, where the three unknown
prices as x = [x1 , x2 , x3 ]T , the coefficient matrix A and the right hand side
matrix b. This can be coded as follows in MATLAB:
1 % %% Price of apples = x1
2 % %% Price of bananas = x2
3 % %% Price of oranges = x3
4
5 % %% set of linear simultaneous equations
6 % %% 3* x1 + 12* x2 + x3 = 236
7 % %% 12* x1 + 2* x3 = 526
8 % %% 2* x2 + 3* x3 = 277
9 % %% Solution
10 % %% Ax = b
11
12 clc ; % clear the command window
13
26 CHAPTER 2. PARTS OF A MATLAB SCRIPT

14 A = [3 12 1; 12 0 2; 0 2 3];
15 b = [236; 526; 277];
16 x = A \ b ;
17 fprintf (" The price list is \ n ") ;
18 fprintf (" Apple - Rs . % f \ n " , x (1) ) ;
19 fprintf (" Banana - Rs . % f \ n " , x (2) ) ;
20 fprintf (" Orange - Rs . % f \ n " , x (3) ) ;
21
22 fprintf (" Solution check 1: Rama ' s expenditure is 3*
x1 + 12* x2 + x3 = % f \ n " , A (1 ,:) * x ) ;
23 fprintf (" Solution check 2: Sita ' s expenditure is
12* x1 + 2* x3 = % f \ n " , A (2 ,:) * x ) ;

2. Ask the user to enter the marks (m) of 10 students. Create a corresponding
list of grades according to

ˆ m ≥90 : S
ˆ 80 ≤ m < 90 : A
ˆ 70 ≤ m < 80 : B
ˆ 60 ≤ m < 70 : C
ˆ 50 ≤ m < 60 : D
ˆ 40 ≤ m < 50 : P
ˆ m < 40 : F

Plot the frequency distribution of grades obtained in the class.

Solution: The problem involves several basic tasks. When writing a


program, it is advisable (i) to identify the series of tasks and then (ii) to
simplify the tasks, (iii) implement the simplified tasks, one at a time, and
(iv) verify each task with a known small set of input data for which the
output after execution of the specific task is also known or can be evaluated
manually. Once each of the simplified tasks are validated one by one and
in sequence for a simplified–but representative–data, then the complexity
of each task may be slowly built into. Such an approach will help in easy
identification of algorithmic errors and coding bugs. Ultimately such an
approach saves a lot of time and avoids a novice programmer being stuck
in the middle of several lines of untested code.
For example, the main tasks for the above problem can be identified as
(i) build a marks vector, (ii) grade the marks, (iii) count the number of
students getting a grade, and (iv) create a bar chart.
Now, the first task of creating the vector of marks actually requires iter-
atively printing a prompt to the terminal and collecting the user entered
marks one by one and store in a marks vector. If we begin with coding an
input collection statements, then during debugging or every test run we
2.9. EXAMPLES 27

need to enter a set of 10 marks. This is tedious and unnecessary during


development. Instead we can begin with a minimal set of representative
marks which are directly hard-coded initially into the MATLAB script:
1 marks = [24 ,98 ,77 ,83 ,58];

This block can later be replaced by a user response collection block, such
as:
1 marks = zeros (10 ,1) ;
2 for i =1:10
3 marks (i ,1) = input (" Enter the marks of the student
: ") ;
4 end

Once we have the marks vector, the next task is to find the grades. Here,
we may initially test with just two grades, say a ’P’ or ’F’ for a cut-off
of 40 marks. Here, we decide to use logical vectors specifying the above
condition on the marks:
1 tf_p = marks >= 40;

will result in the following output for tf p:


1 >> tf_p
2 tf_p =
3
4 0 1 1 1 1

which indicates that except for the first element of the marks vector, all
the elements satisfy the condition. Now the total number of pass students
would simply be the sum of the vector tf p.
1 np = sum ( tf_p ) ;
2 nf = sum (~ tf_p ) ;

Now we can create a grades vector of characters such that


1 grades ( tf_p ) = ' P ' ;
2 grades (~ tf_p ) = ' F ' ;

The result would be:


1 >> grades
2 grades = FPPPP
3 >> np , nf
4 np = 4
5 nf = 1
28 CHAPTER 2. PARTS OF A MATLAB SCRIPT

Once the code for the simplified central tasks is working as desired with
validated output, extensions to other grades is straight forward. In the
following, the number of students obtaining each grade will be stored in a
vector n rather than in individual variable. Thus, the final code could look
like:
1 % marks = zeros (10 ,1) ;
2 % for i =1:10
3 % marks (i ,1) = input (" Enter the marks of the
student : ") ;
4 % end
5
6 % marks = [24 ,98 ,77 ,83 ,58];
7
8 marks = round ( rand (100 ,1) *100) ;
9
10 % create a logical matrix of ' num_students x
num_grades '
11 tf = zeros (100 ,7 , ' logical ' ) ;
12 tf (: ,1) = marks >90;
13 tf (: ,2) = marks <=90 & marks >80;
14 tf (: ,3) = marks <=80 & marks >70;
15 tf (: ,4) = marks <=70 & marks >60;
16 tf (: ,5) = marks <=60 & marks >50;
17 tf (: ,6) = marks <=50 & marks >40;
18 tf (: ,7) = marks <=40;
19
20 % assign the grades
21 list_of_grades ( tf (: ,1) ) = ' S ' ;
22 list_of_grades ( tf (: ,2) ) = ' A ' ;
23 list_of_grades ( tf (: ,3) ) = ' B ' ;
24 list_of_grades ( tf (: ,4) ) = ' C ' ;
25 list_of_grades ( tf (: ,5) ) = ' D ' ;
26 list_of_grades ( tf (: ,6) ) = ' P ' ;
27 list_of_grades ( tf (: ,7) ) = ' F ' ;
28
29 n = sum ( tf ) ;
30
31 % create a bar plot ;
32 figure (1) ;
33 ax = bar ( n ) ;
34 xlabel ( ' Grades ' , ' FontSize ' , 24) ;
35 ylabel ( ' Number of students ' , ' FontSize ' , 24) ;
36 xticklabels ({ ' S ' , ' A ' , ' B ' , ' C ' , ' D ' , ' P ' , ' F ' }) ;
37 set ( gca , ' FontSize ' ,18) ;

The results is a barchar similar to Fig. 2.1.


2.9. EXAMPLES 29

Figure 2.1: Bar chart output of Example 2

The block between lines 21 and 27 can be compacted even further by


replacing with
1 grds ={ ' S ' , ' A ' , ' B ' , ' C ' , ' D ' , ' P ' , ' F ' };
2 for i =1: numel ( grds )
3 list_of_grades (: , i ) = grds { i };
4 end

and the grds cell vector can be used to set the xticklabels:
1 xticklabels ( grd ) ;

3. Consider a set of 102×102 metal atoms on a square lattice. If the po-


tential field can be assumed to be a sinusoidally varying along x− and
y−directions, plot the force field variation on this lattice.

Solution Following the same philosophy outline above, the first task is to
create the potential function as its specific form is not given. For this let us
consider the array of atoms sitting on the square lattice points. Since the
lattice points are equilibrium positions of the atoms, the potential energy
must be a minimum at these locations while it should vary sinusoidally
as the problem states. Thus, the potential energy will have a maximum
half-way between any two adjacent atoms along the basis vectors of the
lattice as shown in Fig. 2.2.
The form of this sine curve is given by
 x
U (x) = − cos 2π (2.1)
a
30 CHAPTER 2. PARTS OF A MATLAB SCRIPT

Since, the problem states that the potential energy also varies sinusoidally
along both the lattice directions, the potential energy can be expressed as
h  x  y i
U (x, y) = −U0 cos 2π + cos 2π . (2.2)
a a
Then, the force field can be obtained as

− →

F = − ∇U. (2.3)

Coding:

Before developing the actual MATLAB script for plotting the force filed,
begin with testing the plots for a 1D lattice:
1 % %% Plot the potential field of an infinite 1 D
lattice around 3 atoms .
2
3 a =3; % lattice parameter
4 x =0: a /30:2* a ;
5 v = - cos (2* pi * x / a ) ;
6
7 figure (1) ;
8 plot (x ,v , ' r - ' , ' LineWidth ' ,2) ;
9 axis ([ -0.2* a 2.2* a -1.2 1.2]) ;
10 grid on ;
11 hold on ;
12 plot ([0 , a ,2* a ] ,[1 ,1 ,1] , ' ko ' , ' markersize ' ,30 , '
markerfacecolor ' , ' b ' , ' markeredgecolor ' , ' k ' ) ;
13 xticks ([0 , a ,( natoms -1) * a ]) ;
14 xticklabels ({ ' 0 ' , ' a ' , ' 2 a ' }) ;
15 set ( gca , ' FontSize ' ,20) ;
16 set ( gca , ' XAxisLocation ' , ' origin ' ) ;
17 set ( gca , ' box ' , ' off ' ) ;
18 ylabel ( ' U ( x ) ' , ' fontsize ' ,24) ;

This produces the Fig. 2.2 and satisfies the required conditions on energy
minima and maxima. Now, the 2D potential field can be constructed
according to the equation 2.2:

2.10 Exercises

1. Write minimalistic code using the colon operator create 1D arrays with
the following values:

(a) a = [1, 2, 3, 4, ..., 100]


2.10. EXERCISES 31

Figure 2.2: Potential field between atoms on a 1D lattice with a sinusoidal


variation.

Figure 2.3: Potential field between atoms on a 1D lattice with a sinusoidal


variation.
32 CHAPTER 2. PARTS OF A MATLAB SCRIPT

(b) b = [1, 3, 5, 7, ..., 101]


(c) c = [5, 10, 15, 20, ..., 200]
(d) d = [100, 99, 98, 97, 96, ..., 0]
1 2 3 4 100
(e) e = [ , , , , ..., ]
100 99 97 96 1
2. Create a vector x with the elements,

(−1)n+1
xn =
(2n − 1)

Add up the elements of the version of this vector that has 100 elements.

3. Write down the MATLAB expression(s) that will

(a) compute the length of the hypotenuse of a right triangle given the
lengths of the sides (try to do this for a vector of side-length values).
(b) compute the length of the third side of a triangle given the lengths of
the other two sides, given the cosine rule

c2 = a2 + b2 − 2ab cos(t)

where t is the included angle between the given sides.

4. Given a vector, t, of length n, write down the MATLAB expressions that


will correctly compute the following:

(a) ln(2 + t + t2 )
(b) et (1 + cos(3t))
(c) cos2 (t) + sin2 (t)
(d) tan−1 (t) (this is the inverse tangent function)
(e) cot(t)
(f) sec2 (t) + cot(t) − 1

Test that your solution works for t = 1:0.2:2.

5. Let x = [3 2 6 8]' and y = [4 1 3 5]' (NB. x and y should be column


vectors).

(a) Add the sum of the elements in x to y


(b) Raise each element of x to the power specified by the corresponding
element in y.
(c) Divide each element of y by the corresponding element in x
(d) Multiply each element in x by the corresponding element in y, calling
the result z.
(e) Add up the elements in z and assign the result to a variable called w.
2.11. FUNCTIONS 33

(f) Compute x'*y - w and interpret the result

6. Find the most efficient way of evaluating


3 1 16
1 − x + x2 + x3
y= 5 20 25
3
4 + x + x2 + x3
4
Remember that using for loops is very much degrading in performance.

7. Generate randomly marks between 0 to 100 for 20 students. Generate a


list of grades corresponding to each student where the grading goes as: ‘S’
for 91-100, ‘A’ for 81-90, ‘B’ for 71- 80, ‘C’ for 61-70, ‘D’ for 51-60, ‘P’ for
40-51, and ‘F’ 0-39. Write a program making use of the function find.

8. The Fibonacci sequence is defined by



1, n = 1;
Fn = (2.4)
1, n = 2; Fn−1 + Fn−2 , n ≥ 3.

Write a script which calculates F20 . Use a for loop. Note that at any
given time you need only store the three active members of the sequence,
say F_curr, F_old, and F_older, which you will “shuffle” appropriately.

9. Using for loop for computing each Fibonacci number, write a script which
finds the sum of the first 100 Fibonacci numbers Fn , 1 ≤ n ≤ 40, for which
Fn is divisible by either 2 or 5.

10. Create a matrix comp to store composition value at 100×100 nodal points
of a discrete domain. Initialize the composition at each node to random
value lying anywhere in the range 0.4999 and 0.5001. If the composition
is between 0.50005 and 0.49985, then overwrite it with 0.5.

11. Create a series of file names containing the file prefix pfx='DATA_' and the
iteration number itr. The iteration counter itr takes values 0, 100, 200,
300, ..., 1000.

2.11 Functions

The regularly used functions are similar to functions in C or FORTRAN. They


receive variables as arguments and return outputs. Typical practice is to write
one function per file. For this function to be callable from other functions in
other files, it is required that the function is the file name but with extension
“.m´´.

The function arguments are passed by default as “smart copy´´ method, i.e.
the original variable is accessed within the called funciton as long as the value
34 CHAPTER 2. PARTS OF A MATLAB SCRIPT

of the variable is not modified. When modified within the funciton, a copy is
created in the local workspace immediately before the modification operation;
the original variable remains unaltered. Thus there is “no passing´´ by reference
method.

The typical syntax is: in a file myfunction.m


1 function [ output1 , output2 , output3 ] = myfunction (
input1 , input2 )
2 output1 = input1 * input2 ;
3 output2 = input1 + input2 ;
4 if ( input1 > input2 ) return ;
5 output3 = input1 / input2 ^ input1 ;
6 end

If an output argument is not required in the calling function, it may not be


received by substituting the output argument in the calling statement by a tilde.
For example say in the function caller_fun contains the following function call
and receives only variables op1 and op2 but ignores the second output variable.
1 [ op1 , ~ , op3 ] = myfuntion ( input1 , input2 ) ;

There are four types of functions in MATLAB:

ˆ Local Functions

ˆ Nested Functions

ˆ Anonymous Functions

ˆ Private Functions

2.11.1 Local functions

A MATLAB file can contain more than one function. It cannot be a script file!
The first function in the file is called the main function and will be accessible from
other functions. The additional functions are then become the local functions
and therefore are only accessible from the main function, but are not callable
from other functions in other files. Note that this behaviour is different from C
or FORTRAN.

As of R2016b, you can also create local functions in a script file, as long as
they all appear after the last line of script code.

Local functions in the current file have precedence over functions in other
files. That is, when you call a function within a program file, MATLAB checks
2.11. FUNCTIONS 35

whether the function is a local function before looking for other main functions.
Therefore, you can create an alternate version of a particular function while
retaining the original in another file.

All functions, including local functions, have their own workspaces that are
separate from the base workspace. Local functions cannot access variables used
by other functions unless you pass them as arguments.

2.11.2 Nested functions

A function nested within another function, for example


1 function [ output1 , output2 , output3 ] = parentfunction (
input1 , input2 )
2 output1 = input1 * input2 ;
3 output2 = input1 + input2 ;
4 temp = nested_fun () ;
5 output3 = input1 / input2 ^ temp ;
6
7 function temp = nested_fun ()
8 temp = input1 * output1 ;
9 end
10 end

As can be seen above, the nested functions are different from the Local Functions
in that they can access the variable in the workspace of its parent function
although they are not passed through the function arguments.

Any variable inside a nested function which is again used in the subsequent
code of the parent function, will become available to the parent function. For
example, in the both the following programs fn_ex_main1 and fn_ex_main2
1 function fn_ex_main1
2 x = 5;
3 nested_fun ()
4 fprintf ( ' x = % f ' , x ) ;
5
6 function nested_fun ()
7 x = x + 1;
8 end
9
10 end

and
1 function fn_ex_main2
36 CHAPTER 2. PARTS OF A MATLAB SCRIPT

2 nested_fun ()
3
4 function nested_fun ()
5 x = 5;
6 end
7 x = x +5;
8 fprintf ( ' x = % f ' , x ) ;
9 end

Any further variables defined inside the nested function and those that are
not used by the parent function after a calle to the nested function are local to
itself and are cleared upon returning the control back to the parent function and
thus are not available to the parent function.

If the same variable name is used in more than two nested functions and
is not at all used by the parent function, then that variable becomes a local
variable. For example, in
1 function fn_ex_main2
2 nested_fun1 ()
3 nested_fun2 ()
4
5 function nested_fun2 ()
6 x = 5;
7 end
8 function nested_fun1 ()
9 x = 7;
10 end
11 end

the variable x is local to the nested functions.

Scope of nested functions: The nested function is visible only to the level
immediately above it. For example in the following code, function A can call B
or D, but not C or E.
1 function main (x , y ) % Main function
2 sub_fun1 (x , y )
3 sub_fun2 ( y )
4
5 function sub_fun1 (x , y ) % Nested in main
6 subsub_fun1 ( x )
7 sub_fun2 ( y )
8
9 function subsub_fun1 ( x ) % Nested in
sub_fun1
2.12. DATA IMPORT AND EXPORT 37

10 sub_fun2 ( x )
11 end
12 end
13
14 function sub_fun2 ( x ) % Nested in main
15 subsub_fun2 ( x )
16
17 function subsub_fun2 ( x ) % Nested in
sub_fun2
18 disp ( x )
19 end
20 end
21 end

2.12 Data import and export

The low level functions such as fscanf, fprintf, fread, fwrite, fgets,
feof, fopen, fclose, ... are also available in MATLAB, and follow the
same syntax as in C. See MATLAB online help for more information and practice.

2.12.1 The importdata function

The simple function call a=importdata(filename); imports and loads the data
from the file in the string filename into an array a.

The delimiter, by default, is assumed to be a series of white spaces. In case


of other delimiters, they can be explicitly specified by the optional argument
delimiter. Also the number of header lines can be specified which will be
skipped while import. For example, to read a file mydata.dat containing
1 Sun Mon Tue Wed Thu Fri
Sat
2 95.01 76.21 61.54 40.57 55.79 70.28
81.53
3 73.11 45.65 79.19 93.55 75.29 69.87
74.68
4 60.68 41.85 92.18 91.69 81.32 90.38
74.51
5 48.60 82.14 73.82 41.03 0.99 67.22
93.18
6 89.13 44.47 57.63 89.36 13.89 19.88
46.60
38 CHAPTER 2. PARTS OF A MATLAB SCRIPT

the script may look like


1 filename = ' mydata . dat ' ;
2 delimiter = ' ' ;
3 numHdrlines = 1;
4 A = importdata ( filename , delimiter , numHdrlines ) ;
5 % View data
6 for k = [1:7]
7 disp ( A . colheaders {1 , k })
8 disp ( A . data (: , k ) )
9 disp ( ' ' )
10 end

2.12.2 The load function

It loads variables from a file into workspace (along with their variable names if
the file is written in MATLAB’s native save function), or reads and returns an
array of data written in an ascii file.

For example,
1 load gong . mat

or
1 load ( ' gong . mat ' ) ;

In both cases check the MATLAB workspace.

Similarly, to write a given set of variables from the current workspace in the
MATLAB’s compact native output format, one can use
1 p = rand (1 ,10) ;
2 q = ones (10) ;
3 save ( ' pqfile . mat ' , ' p ' , ' q ' ) ;

or simply
1 save pqfile . mat p q

or to save in ascii format


1 save ( ' pqfile . txt ' , ' p ' , ' q ' , ' - ascii ' )
Chapter 3

Basic Plotting

MATLAB has functions which will enable plotting of data in a variety of ways
in 2D and in 3D. Refer to MATLAB/doc for some useful functions such as plot,
plot3d, subplot, contour, contourf, isosurf, trisurf, bar, hist, scatter,
polar, loglog, semilogx, semilogy, etc.

3.1 Line plots

Let us examine the plotting features from MATLAB using a familiar example.
The following equation is known as the Ramberg-Osgood relation, which is ca-
pable of describing the stress-strain response of many metals and alloys:
 n
σ σ
ε= +α (3.1)
E σ0

Assuming E = 200 GPa, n = 20, σ0 = 150 MPa, and α = 0.002, we plot


the stress-strain curve using the following script, which produces the figure in
Fig. 3.2(b).
1 clear all ; % clears the current workspace
2 close all ; % closes all the figures
3 clc ; % clear the terminal output
4
5 E =200 e9 ;
6 sigma_0 =150 e6 ;
7 n =20;
8 alpha =0.002;
9 sig = 0:1 e4 :1.65 e8 ;
10 eps = sig / E + alpha *( sig / K ) .^ n ;
11
12 figure (1) ;

39
40 CHAPTER 3. BASIC PLOTTING

13 plot ( eps *100 , sig /1 e6 , ' - ' ) ;


14 xlabel ( ' Strain [%] ' ) ;
15 ylabel ( ' Stress [ MPa ] ' ) ;

(a) (b)

Figure 3.1: Examples of a line plots.

Now let us see, how to produce data symbols, line colours and types, annotate
with text, produce legend, and control appearance of the figure and font sizes.
The below code produces the Fig. 3.1(b).
1 clear all ; % clears the current workspace
2 close all ; % closes all the figures
3
4 a = [1 2 4];
5 x = 0:1 e -1:1;
6 y = a (1) + a (2) * x + a (3) * x .^2;
7
8 figure (1) ;
9 plot (x ,y , ' rd - - ' , ' LineWidth ' , 1.5 , ...
10 ' MarkerSize ' ,10 , ' MarkerEdgeColor ' , ' none ' , ...
11 ' MarkerFaceColor ' , [.4 1 .3]) ;
12 hold on ;
13
14 z = x .^2/ a (2) + a (3) * x .^3;
15 plot (x ,z , ' bo - ' , ' LineWidth ' , 1.5 , ...
16 ' MarkerSize ' ,10 , ' MarkerEdgeColor ' , ' none ' , ...
17 ' MarkerFaceColor ' , [.8 0.2 .8]) ;
18 xlabel ( '$ x $ ' , ' FontSize ' , 14 , ' interpreter ' , ' latex ' ) ;
19 ylabel ( '$ a_1 + a_2 x + a_3 x ^2; \ quad \ frac {1}{ a_2 } x ^2
+ a_3 x ^3 $ ' , ' FontSize ' , 14 , ' interpreter ' , ' latex '
);
20
21 axis square
3.2. SURFACE PLOTS AND CONTOURS 41

22 axis ([0 1 1 5]) ;


23
24 text (0.1 , 3 , '$ a_1 + a_2 x + a_3 x ^2 $ ' , ' FontSize ' , 14 ,
' interpreter ' , ' latex ' ) ;
25 text (0.7 , 1.3 , ' $ \ frac {1}{ a_2 } x ^2 + a_3 x ^3 $ ' , '
FontSize ' , 14 , ' interpreter ' , ' latex ' ) ;
26
27 title ( ' My Functions ' ) ;
28 legend ({ '$ a_1 + a_2 x + a_3 x ^2 $ ' , ' $ \ frac {1}{ a_2 } x ^2 +
a_3 x ^3 $ ' } , ...
29 ' location ' , ' northwest ' , ...
30 ' interpreter ' , ' latex ' , ...
31 ' FontSize ' , 18) ;
32 legend ( ' boxoff ' ) ;

3.1.1 Two y-axes

An example from MATLAB’s documentation:


1 x = 0:0.01:20;
2 y1 = 200* exp ( -0.05* x ) .* sin ( x ) ;
3 y2 = 0.8* exp ( -0.5* x ) .* sin (10* x ) ;
4
5 figure % new figure
6 [ hAx , hLine1 , hLine2 ] = plotyy (x , y1 ,x , y2 ) ;
7
8 title ( ' Multiple Decay Rates ' )
9 xlabel ( ' Time (\ musec ) ' )
10
11 ylabel ( hAx (1) , ' Slow Decay ' ) % left y - axis
12 ylabel ( hAx (2) , ' Fast Decay ' ) % right y - axis

3.2 Surface plots and contours

To create the following figures:

use the code


1 clc ;
2 clear all ;
3
4 x =0:1 e -2:1;
5
42 CHAPTER 3. BASIC PLOTTING

(a) (b)

(c) (d)

Figure 3.2: Surface and filled contour plots


3.2. SURFACE PLOTS AND CONTOURS 43

6 N = numel ( x ) ;
7
8 cent =[ x ( int32 ( N /2) ) ,x ( int32 ( N /2) ) ];
9 sig =0.2;
10 gs = zeros (N , N ) ;
11 for i =1: N
12 for j =1: N
13 gs (i , j ) = exp ( -(( x ( i ) -x ( int32 ( N /2) ) ) / sig ) ^2) *
exp ( -(( x ( j ) -x ( int32 ( N /2) ) ) / sig ) ^2) ;
14 rn (i , j ) = exp ( -(( x ( i ) -x ( int32 ( N /4) ) ) / sig ) ^2) *
exp ( -(( x ( j ) -x ( int32 ( N /10) ) ) / sig ) ^2)...
15 + gs (i , j ) *0.5 ...
16 + 0.25*( exp ( -(( x ( i ) -x ( int32 ( N /3) ) ) / sig ) ^2)
* exp ( -(( x ( j ) -x ( int32 ( N /5) ) ) / sig ) ^2) )
...
17 + 0.25*( exp ( -(( x ( i ) -x ( int32 ( N /10) ) ) / sig )
^2) * exp ( -(( x ( j ) -x ( int32 ( N /3) ) ) / sig ) ^2) )
...
18 + 0.25*( exp ( -(( x ( i ) -x ( int32 ( N /10) ) ) / sig )
^2) * exp ( -(( x ( j ) -x ( int32 ( N /10) ) ) / sig )
^2) ) ;
19 end
20 end
21 figure (1) ;
22 surf ( gs , ' EdgeColor ' , ' None ' ) ;
23 xlabel ( '$ x $ ' , ' FontSize ' , 14 , ' Interpreter ' , ' latex ' ) ;
24 ylabel ( '$ y $ ' , ' FontSize ' , 14 , ' Interpreter ' , ' latex ' ) ;
25 zlabel ( '$ C (x , y ) $ ' , ' FontSize ' , 14 , ' Interpreter ' , '
latex ' ) ;
26 camlight right ;
27 lighting phong ;
28 axis tight
29
30 sig =0.1;
31 rn = zeros (N , N ) ;
32 for i =1: N
33 for j =1: N
34 rn (i , j ) = gs (i , j ) +( exp ( -(( x ( i ) -x ( int32 ( N /4) ) ) / sig )
^2) * exp ( -(( x ( j ) -x ( int32 ( N /10) ) ) / sig ) ^2) )...
35 +( exp ( -(( x ( i ) -x ( int32 ( N /7) ) ) / sig ) ^2) * exp ( -(( x (
j ) -x ( int32 ( N /4) ) ) / sig ) ^2) )...
36 +( exp ( -(( x ( i ) -x ( int32 ( N /1.3) ) ) / sig ) ^2) * exp ( -((
x ( j ) -x ( int32 ( N /7) ) ) / sig ) ^2) )...
37 +( exp ( -(( x ( i ) -x ( int32 ( N /1.3) ) ) / sig ) ^2) * exp ( -((
x ( j ) -x ( int32 ( N /1.5) ) ) / sig ) ^2) )...
38 +( exp ( -(( x ( i ) -x ( int32 ( N /1.5) ) ) / sig ) ^2) * exp ( -((
44 CHAPTER 3. BASIC PLOTTING

x ( j ) -x ( int32 ( N /1.1) ) ) / sig ) ^2) ) ;


39 end
40 end
41 figure (2) ;
42 surf ( rn , ' EdgeColor ' , ' None ' ) ;
43 xlabel ( '$ x $ ' , ' FontSize ' , 14 , ' Interpreter ' , ' latex ' ) ;
44 ylabel ( '$ y $ ' , ' FontSize ' , 14 , ' Interpreter ' , ' latex ' ) ;
45 zlabel ( '$ C (x , y ) $ ' , ' FontSize ' , 14 , ' Interpreter ' , '
latex ' ) ;
46 % camlight right ;
47 % lighting phong ;
48 axis tight
3.3. EXERCISES 45

3.3 Exercises

1. Write a function to receive a matrix

(a) subtract 5 from each element and return back the matrix
(b) return the number of positive numbers
(c) return the locations of the elements greater than the mean of all the
elements

2. The Taylor series expansion of the exponential function is



x
X xn
e = n≥0
n!
n=0

In one figure, plot and compare ex from the intrinsic function exp(x) with
the above expansion for different n = 1, 2, 3, 5, 7, 11. In a second figure,
plot the error/residual for every n.

3. Repeat the above for the series expansion for sine but plot the curves for
every n in a separate subplot (see subplot command of MATLAB). Plot
the function and their errors on the same subplot.

4. Given a set of simultaneous equations

x − 2y + 3z = 7
2x + y + z = 4
−3x + 2y − 2z = −10

Find their solution using matrix method. Also show graphically that the
solution is correct by plotting the three lines in a three dimensional line
plot using plot3 command.

5. Write a MATLAB script that generates a matrix of 10×10 random numbers


lying between -10000 and 10000 representing field values of a concentration
variable c on 10 × 10 nodal grid; and

(a) saves the matrix to a disk


(b) write another script to read the above data and plot it as a filled
contour of a grid 10x10 with dx = dy = 1.
(c) On this grid each node (i, j) has neighbours. The number of neigh-
bours may vary for interior nodes and nodes on the boundary. Create
neighbour list for each node. The neighbour list of a node (i, j) should
contain the value of the concentration (field value).

6. Write a script to do the following: On a single figure, plot the functions


sinh(x), x cosh(x), tanh(x), and ex for −1 ≤ x ≤ 1, with point spacing
1
∆x = 10 . Make sinh a red line, cosh a black dotted line, tanh a blue
46 CHAPTER 3. BASIC PLOTTING

line with circles at each point, and ex just green ×’s with no line. Make
a legend. Label your axes and give the figure a title. Use linspace to
create a vector of x values and call each Matlab mathematical function
with vector arguments to create the corresponding vector of “y” values.

7. Generate a set of random points {(xi , yi ) : xi , yi ∈ [0, 5] ∀ i = 1, 2, 3, ..., 20}.


Round them to the nearest second decimal. Remove any duplicate points.
Use delaunay function to triangulate the domain enclosed by these random
points. The result is a triangular mesh. Plot this triangular mesh using
plot function. Also, learn to use the triplot command to do the same.

Вам также может понравиться