Академический Документы
Профессиональный Документы
Культура Документы
1
Lecture Notes: ML3L009
1
Disclaimer: This is a draft still under development, and is therefore incomplete,
may contain errors, typos, etc. Use with caution.
2
Contents
2.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.7 if constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.8 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.9 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.10 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.11 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3 Basic Plotting 39
3
4 CONTENTS
3.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Chapter 1
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.
5
6 CHAPTER 1. THE MATLAB ENVIRONMENT
Chapter 2
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.
7
8 CHAPTER 2. PARTS OF A MATLAB SCRIPT
Some names are reserved for intrinsic function names. It is therefore advisable
not to reuse in your code for other purposes.
2.2.5 Cell
double(n)
int8(x)
uint16(p)
int2str(x)
num2str(p)
...
isinteger(x)
isflaot(p)
ischar(a)
isreal(r)
isvector(amat)
isnumeric(abc)
isscalar(pressure)
2.3.1 Vectors
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
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.
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.
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
Sorting
Slicing/range/subarrays
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
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
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
4. Bitwise operators
5. Set operators
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
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
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
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
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
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.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
1 if ( a (2) >0.5)
2 a (2) = a (2) +100;
3 else
4 a (2) = a (2) *2;
5 end
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
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
1 a =15;
2 while ( a < 20 )
3 fprintf ( ' value of a : % d \ n ' , a ) ;
4 a = a + 1;
5 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
for and while can be nested any number of times and in any manner.
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
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;
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 ) ;
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) ;
and the grds cell vector can be used to set the xticklabels:
1 xticklabels ( grd ) ;
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:
(−1)n+1
xn =
(2n − 1)
Add up the elements of the version of this vector that has 100 elements.
(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)
(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
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 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.
Local Functions
Nested Functions
Anonymous Functions
Private 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.
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
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
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.
The simple function call a=importdata(filename); imports and loads the data
from the file in the string filename into an array a.
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 ' ) ;
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
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.
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
39
40 CHAPTER 3. BASIC PLOTTING
(a) (b)
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
(a) (b)
(c) (d)
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
3.3 Exercises
(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
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.
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.
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.