Introduction To Octave - Sandeep Nagar
Introduction To Octave - Sandeep Nagar
www.bookmuft.com
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
2
Introduction to Octave
For Scientists and Engineers
2
Contents
1 Introduction to Octave 9
1.1 Introduction to numerical computing . . . . . . . . . . . . . . 9
1.2 Various alternatives . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 M AT LAB R and Octave . . . . . . . . . . . . . . . . . . . . 10
1.4 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5 Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5.1 Calculator . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5.2 Predefined constants . . . . . . . . . . . . . . . . . . . 12
1.5.3 Common mathematical functions . . . . . . . . . . . . 12
1.6 help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.7 Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.7.1 Data types . . . . . . . . . . . . . . . . . . . . . . . . 15
1.7.2 Naming conventions for variables . . . . . . . . . . . . 16
1.7.3 List of variables . . . . . . . . . . . . . . . . . . . . . . 18
1.7.4 Global and Local Variables . . . . . . . . . . . . . . . 18
1.7.5 clear . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
2.3.2 Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.3.3 Using indices to make new vector . . . . . . . . . . . . 31
2.3.4 Slicing . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.4 Automatic generation of vectors . . . . . . . . . . . . . . . . . 32
2.4.1 Linearly spaced vector . . . . . . . . . . . . . . . . . . 33
2.4.2 logspace . . . . . . . . . . . . . . . . . . . . . . . . . . 34
2.5 Matrix manipulations . . . . . . . . . . . . . . . . . . . . . . 34
2.5.1 Flipping a matrix . . . . . . . . . . . . . . . . . . . . . 34
2.5.2 Rotating a matrix . . . . . . . . . . . . . . . . . . . . 35
2.5.3 Reshaping a matrix . . . . . . . . . . . . . . . . . . . 35
2.5.4 Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.6 Special matrices . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.6.1 Upper and Lower triangular matrix . . . . . . . . . . 36
2.6.2 Ones and zeros matrix . . . . . . . . . . . . . . . . . . 37
2.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3 Plotting 39
3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.1.1 2D plotting . . . . . . . . . . . . . . . . . . . . . . . . 40
3.1.2 3D plots . . . . . . . . . . . . . . . . . . . . . . . . . . 46
3.2 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4
Dr. Sandeep Nagar
sandeep.nagar@gmail.com www.bookmuft.com
5.2.2 do-until . . . . . . . . . . . . . . . . . . . . . . . . . . 65
5.2.3 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
5.2.4 if-elseif-else . . . . . . . . . . . . . . . . . . . . . . . . 67
5.3 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.3.1 function . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.3.2 inline . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.3.3 Anonymous function . . . . . . . . . . . . . . . . . . . 71
5.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
License
License type:
information
Attribution-NonCommercial-ShareAlike 4.0 Inter-
national License
Present book is presented under Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International
license under which:
You are free to:
Share — copy and redistribute the material in any medium
or format Adapt — remix, transform, and build upon the
material
More information at http://creativecommons.org/
licenses/by-nc-sa/4.0/
6
Dr. Sandeep Nagar
sandeep.nagar@gmail.com www.bookmuft.com
7
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
8
Introduction to Octave
1
1.1 Introduction to numerical computing
9
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
to simulate otherwise impossible tasks.
R
1.3 M AT LAB and Octave
Octave is a opensource alternative which can run MATLAB R code. So
existing MATLAB R users can swiftly change to this new system. Also new
users can learn to code in octave and then shift to MATLAB R environment
as and when required. GNU Octave, version 3.8.1 comes with a Graphic
User Interface (GUI), hence it has been chosen for the present book. Older
and future versions will also run well for the codes presented in the book,
provided future versions choose to remain compatible with present version.
1.4 Installation
Please note that following instructions are valid for Octave, version 3.8.1
only. GNU octave can be downloaded from the url https://www.gnu.org/
software/octave/download.html as per the operating system. Installation
is quite straight forward and user forums or simple google search yields
useful answers to common problems encountered by users. As explained
earlier version 3.8.1 comes with a GUI, hence it is advised that this should
be installed for forthcoming discussions, but all older version will prove to
be equally good.
1.5 Workspace
There are two ways to work within octave. First one is to work at command
line by writing one command at a time. Second method is to write a script
(a .m file having a set of commands in a sequence) and running it from the
command line by simply writing its name. For example to run a.m script
file, one simply writes at command prompt:
1 >>a
1.5.1 Calculator
In simplest view, octave works as a calculator with mathematical operators
like multiplication (symbol is *), division (symbol is /), addition (symbol is
+), substraction (symbol is -) and exponentiation(symbol is ^):
1 >> 3 + 5
2 ans = 8
1 >> p i
2 ans = 3 . 1 4 1 6
3 >> e
4 ans = 2 . 7 1 8 3
5 >> i
6 ans = 0 + 1 i
7 >> j
8 ans = 0 + 1 i
9 >> I n f / I n f
10 ans = NaN
1.6 help
Covering all the functions available with octave is beyond the scope of the
present book. To understand how a particular function needs to be used,
one can use help() command where argument can be the function whose
usage needs to be found out. For example help(exp) gives a detailed view
about how this function should be used.
1 >> h e l p exp
2 ’ exp ’ i s a b u i l t −i n f u n c t i o n from t h e f i l e libinterp / corefcn /
mappers . c c
3
4 −− Mapping Function : exp (X)
5 Compute ’ e ˆx ’ f o r each e l e m e n t o f X. To compute t h e matrix
6 e x p o n e n t i a l , s e e ∗ n o t e L i n e a r Alg ebra : : .
7
8 See a l s o : l o g .
9
10
11 A d d i t i o n a l h e l p f o r b u i l t −i n f u n c t i o n s and o p e r a t o r s i s
12 a v a i l a b l e i n t h e o n l i n e v e r s i o n o f t h e manual . Use t h e command
13 ’ doc <t o p i c > ’ t o s e a r c h t h e manual i n d e x .
14
15 Help and i n f o r m a t i o n about Octave i s a l s o a v a i l a b l e on t h e WWW
16 a t h t t p : / /www. o c t a v e . o r g and v i a t h e h e l p @ o c t a v e . o r g
17 mailing l i s t .
1.7 Variable
To store values temporarily, we use variables which store the value at a
particular memory location and address it with a symbol or set of symbols
1 >> a=1/10∗ p i
2 a = 0.31416
3 >> a ˆ2 + 10∗ s q r t ( a )
4 ans = 5 . 7 0 3 7
• char: This type of data stores alphabetic characters and strings (group
of characters written in a sequence).
• double, single This type of data is stored as double and single pre-
cision floating type respectively. Decimal numbers are represented by
floating point data types. Single precision occupies 4 bytes (32 bits)
and double precision occupies (64 bits) to store the floating point num-
bers.
In single precision system, 23 bits stores the fraction bits (i.e num-
bers after the decimal point), 8 bits stores the exponent (i.e the num-
bers before the decimal point) and 32nd bit is reserved for storing the
sign.
In double precision system, 52 bits stores the fraction bits (i.e
numbers after the decimal point), 11 bits stores the exponent (i.e the
numbers before the decimal point) and 64th bit is reserved for storing
the sign.
Single and double precision matters when precision of result mat-
ters. In cases like GPS position for a projectile flying at high speeds,
it will be required that the results should be as precise as possible for
greater accuracy of hit.
• Names should not start with a number however numbers can be used
anywhere afterwards.
While naming a variable, if one needs to check that the name given is
a keyword or not, then one can use a built-in function iskeyword(name).
Simply writing iskeyword() produces a list of keywords as shown below:
1 >> i s k e y w o r d ( )
2 ans =
3 {
4 [1 ,1] = FILE
5 [2 ,1] = LINE
6 [ 3 , 1 ] = break
7 [ 4 , 1 ] = case
8 [ 5 , 1 ] = catch
9 [6 ,1] = classdef
10 [ 7 , 1 ] = continue
11 [ 8 , 1 ] = do
12 [9 ,1] = else
13 [10 ,1] = e l s e i f
14 [ 1 1 , 1 ] = end
15 [12 ,1] = end try catch
16 [ 1 3 , 1 ] = end unwind protect
17 [14 ,1] = endclassdef
18 [ 1 5 , 1 ] = endenumeration
19 [ 1 6 , 1 ] = endevents
20 [ 1 7 , 1 ] = endfor
21 [ 18 , 1] = endfunction
22 [19 ,1] = endif
23 [ 2 0 , 1 ] = endmethods
24 [ 2 1 , 1 ] = endparfor
25 [22 ,1] = endproperties
26 [ 2 3 , 1 ] = endswitch
27 [ 2 4 , 1 ] = endwhile
28 [ 2 5 , 1 ] = enumeration
29 [ 2 6 , 1 ] = events
30 [27 ,1] = for
31 [28 ,1] = function
32 [29 ,1] = global
33 [30 ,1] = i f
34 [ 3 1 , 1 ] = methods
35 [32 ,1] = otherwise
36 [33 ,1] = parfor
37 [34 ,1] = persistent
38 [35 ,1] = properties
39 [36 ,1] = return
40 [37 ,1] = static
41 [ 3 8 , 1 ] = switch
42 [39 ,1] = try
43 [40 ,1] = until
By using who and whos one can keep track of memory requirements
judicious use of memory resources are important such as Raspberry Pi based
systems.
1 >> g l o b a l a =1
2 >> g l o b a l a = 2
3 >> a
4 a = 1
5 >> c l e a r
6 >> who
7 >> whos
8 >> a=1
9 a = 1
10 >> a=2
11 a = 2
12 >>
1.7.5 clear
As seen in previous section, clear command flushes out variable names and
their values from the memory. It proves to be much more useful than that.
Whereas clear all is same as clear, it can also be used to selectively wipe
out variables and their values. Simply type help clear gives a detailed view
of its use:
1 >> h e l p c l e a r
2 ’ c l e a r ’ i s a b u i l t −i n f u n c t i o n from t h e f i l e libinterp / corefcn /
v a r i a b l e s . cc
3
4 −− Command : c l e a r [ o p t i o n s ] p a t t e r n . . .
5 D e l e t e t h e names matching t h e g i v e n p a t t e r n s from t h e symbol
table .
6 The p a t t e r n may c o n t a i n t h e f o l l o w i n g s p e c i a l c h a r a c t e r s :
7
1.8 Summary
Using octave as a simple calculator (using numbers and basic operations)
as well as a complex calculator (using variables with complex functions),
one can perform numerical calculation at ease. Learning curve for octave
is quite flat owing to is simple and intuitive syntax. In case of confusion,
documentation for particular commands can be easily available using help
command. Octave also provides an integrated environment for working with
a lot of different kinds of computational tasks.
Octave has a class of objects for dealing with matrices. They are called
arrays. Using different properties of this class, one can define various kinds
of matrices. Built-in functions for matrix operations make it easier for a
programmer to deal with large number of data by arranging them as a
matrix in the desired format and performing array operations.
23
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
2.2 Arrays and vectors
Instead of just pointing to a single number, a variable name can also point
to a sequential set of numbers called an array.
1 >> a = [ 1 , 2 , 3 , 4 , 5 ]
2 a =
3
4 1 2 3 4 5
5
6 >> a1 = [ 1 0 , 1 1 , 1 2 , 1 3 , 1 4 ]
7 a1 =
8
9 10 11 12 13 14
10 >> m at ri x 22 = [ 1 , 2 ; 3 , 4 ]
11 m at ri x 22 =
12
13 1 2
14 3 4
15 >> m at ri x 33 = [ 1 , 2 , 3 ; 4 , 5 , 6 ; 7 , 8 , 9 ]
16 m at ri x 33 =
17
18 1 2 3
19 4 5 6
20 7 8 9
21 >> s i z e ( a )
22 ans =
23
24 1 5
25
26 >> s i z e ( m at ri x 22 )
27 ans =
28
29 2 2
30
31 >> s i z e ( m at ri x 33 )
32 ans =
33
34 3 3
Line number 14 shows that if the element is set to int16 then it can store
a maximum value of 32767 irrespective of being commanded to store a value
bigger than that. Hence it becomes supremely important to understand the
data-type of the elements beforehand, to avoid errors in numerical calcula-
tions. Also storing very small numbers in larger number of bits is a waste
of memory system (line number 46 displays that the number 1 is stored as
a double precision floating point number which occupies 64 bits where es-
sentially 63 bits except the last one are all zeros).
All arithmetic operators like +,-,*,/, %,^ etc. can be used in both
cases. When we need to do element wise operation, then a . is placed before
operator so that element-wise operators become .+,.-,.*,./, .%,.^. This
will become more clear in following example.
1 >> a = [ 1 , 2 ; 3 , 4 ]
2 a =
3
4 1 2
5 3 4
6
7 >> b = [ 5 , 6 ; 7 , 8 ]
8 b =
9
10 5 6
11 7 8
12
13 >> a+b
14 ans =
15
16 6 8
17 10 12
18
19 >> 2.+ a
20 ans =
21
22 3 4
23 5 6
24
25 >> −10.+b
26 ans =
27
28 −5 −4
29 −3 −2
Those who are familiar with matrix algebra, know that matrix multipli-
cation and division is not a straightforward task. A aXb matrix can only
be multiplied by a bXc matrix which results in aXc matrix and it is per-
formed by multiplying elements of rows with elements of columns to get
new elements.
a’ gives the transpose of a matrix (rows are made columns and vice
versa).
a ∗ a−1 = I
I is called an identity matrix because all its diagonal elements are 1 and
all non-diagonal elements are zero, which makes its determinant 1. Deter-
minant of a matrix a is calculated by the command det(a).
Please note that the numbers generated above will be different each time
even on same machine since they are supposed to be random in nature. By
default, they are uniformly distributed over the interval (0, 1). A vector is
simply a row vector so it can be generated randomly by command rand(a).
help rand gives detailed description about various other features and argu-
ments of random number generator.
2.3.2 Indexing
Each element of the matrix is characterized by two numbers, the row number
and the column number. This is used to pinpoint an element and operate
on that.
1 >> a = rand ( 2 , 3 )
2 a =
3
4 0.5248873 0.5531882 0.0051345
5 0.1597312 0.3685503 0.3041072
6
7 >> a ( 2 , 3 ) =1
8 a =
9
10 0.5248873 0.5531882 0.0051345
11 0.1597312 0.3685503 1.0000000
12
13 >> a ( 1 , 1 ) =0
14 a =
15
Please note that a(2,3)=1 sets the element at 2nd row and 3rd column
i.e. number 0.3041072 to 1 and a(1,1)=0sets the element at 1st row and
1st column i.e. number 0.5248873 to 0. To index numbers in a vector, one
needs a single number.
1 >> a = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
2 a =
3
4 1 2 3 4 5 6 7 8 9
5
6 >> a ( 1 )
7 ans = 1
8 >> a ( −1)
9 e r r o r : s u b s c r i p t i n d i c e s must be e i t h e r p o s i t i v e i n t e g e r s l e s s
than 2ˆ31 o r l o g i c a l s
10 >> a ( 5 )
11 ans = 5
12 >> a ( 1 0 )
13 e r r o r : A( I ) : i n d e x out o f bounds ; v a l u e 10 out o f bound 9
14 >>
1 >> a = [ 1 0 20 30 40 50 6 0 ]
2 a =
3
4 10 20 30 40 50 60
5
6 >> b = a ( [ 1 3 6 1 ] )
7 b =
8
9 10 30 60 10
1 >> a = [ 1 1 , 1 2 , 1 3 ; 4 0 , 5 0 , 6 0 ; 1 7 , 1 8 , 1 9 ]
2 a =
3
4 11 12 13
5 40 50 60
6 17 18 19
7
8 >> a ( [ 1 , 2 ] , [ 2 , 3 ] )
9 ans =
10
11 12 13
12 50 60
2.3.4 Slicing
Matrices can be sliced to desired portions by using indices and colon :
operator.
1 >> a = [ 1 2 3 4 1 3 2 4 6 4 5 ]
2 a =
3
4 1 2 3 4 1 3 2 4 6 4 5
5
6 >> b =a ( 1 : 5 )
7 b =
8
9 1 2 3 4 1
10
11 >> c = a ( 5 : 7 )
12 c =
13
14 1 3 2
Please note that [] are optional here. If step is not defined then it is taken
as 1.
1 >> a =1:10
2 a =
3
4 1 2 3 4 5 6 7 8 9 10
5
6 >> a = 1 : 2 : 1 0
7 a =
8
9 1 3 5 7 9
2.5.4 Sorting
Numbers can be sorted in increasing order using sort function:
1 >> a = rand ( 1 , 5 )
2 a =
3
4 0.577290 0.079980 0.880757 0.294744 0.964269
5
6 >> s o r t ( a )
7 ans =
8
9 0.079980 0.294744 0.577290 0.880757 0.964269
2.7 Summary
Array based computing lies at the very heart of modern computational tech-
niques. Octave presents a very suitable platform to perform this technique
with ease. A variety of predefined functions enable user to save time while
prototyping a problem. Flexible methods to define multidimensional arrays
39
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
3.1.1 2D plotting
plot(x,y)
Since we need data on two axes to be plotted, we first need to create them.
Lets assume that x axis has 100 linearly space data points on which y = x2 .
1 >>x = l i n s p a c e ( 0 , 1 0 0 , 1 0 0 ) ;
2 >> y = x . ˆ 2
3 >> p l o t ( x , y )
Figure 3.1: y = x2
First we defined a variable x and placed 100 equally spaced data points
from 0 to 100. This made a 1x100 matrix. Using scalar operation of expo-
nentiation, we defined a variable y as x2 . Then we use the function plot()
which takes two arguments as x-axis and y-axis data points.
Writing help plot on the command prompt gives useful insight into
this wonderful function written to plot two dimensional data.
40 CHAPTER 3. PLOTTING
Dr. Sandeep Nagar
sandeep.nagar@gmail.com www.bookmuft.com
polar
Sometimes we prefer to plot in polar coordinates, rather than Cartesian
coordinates. Then instead of x, y our coordinates are r, θ.
1 theta = 0 : 0 . 0 2 : 2 ∗ pi ;
2 a1 = 0 . 5 + 1 . 3 . ˆ t h e t a ;
3 a2 = 5 ∗ c o s ( t h e t a ) ;
4 a3 = 3 ∗ ( 1 − c o s ( t h e t a ) ) ;
5 a4 = 6∗ s i n ( 4 ∗ t h e t a ) ;
6 r = [ a1 ; a2 ; a3 ; a4 ] ;
7 PolarGraph = p o l a r ( t h e t a , r , ” ∗ ” ) ;
8 s e t ( PolarGraph , ” LineWidth ” , 2 ) ;
9 l e g e n d ( ” s p i r a l ” , ” c i r c l e ” , ” h e a r t ” , ” Rose ” ) ;
CoordinatesPolar.m
Figure 3.2 gives an example of a polar graph for code given by CoordinatesPolar.m
example. Explanation of program is given as follows(according to line num-
ber):
CHAPTER 3. PLOTTING 41
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
1. A variable named th representing θ is defined by points starting from
0 to 2π with steps of 0.02.
r = 1.5(θ)
r = 5(cos(θ))
r = 3(1 − cos(θ))
r = 6(sin(4θ))
8. set function is used to set the property values for the graph function.
This is a neat way of setting properties of the graph and experimenting
with them later. In present case, property named LineWidth is set to
be 2.
9. legend() function sets four legends in the same order as the polar
function has taken them from the vector r
42 CHAPTER 3. PLOTTING
Dr. Sandeep Nagar
sandeep.nagar@gmail.com www.bookmuft.com
6 y3 = x . ˆ 2 . 2 ;
7 y4 = x . ˆ 2 . 3 ;
8 p l o t ( x , y1 , ”@12” , x , y2 , x , y3 , ” 4 ” , x , y4 , ”+” )
9 g r i d on
10 l e g e n d ( ’ x ˆ2 ’ , ’ x ˆ { 2 . 1 } ’ , ’ x ˆ { 2 . 2 } ’ , ’ x ˆ { 2 . 3 } ’ ) ;
11 x l a b e l ( ’ x−a x i s ’ )
12 y l a b e l ( ’ y−a x i s ’ )
13 t i t l e ( ’ M u l t i p l e Graphs ’ )
14
15 %p l o t y with p o i n t s o f type 2 ( d i s p l a y e d a s ‘+ ’)
16 %and c o l o r 1 ( r e d ) , y2 with l i n e s , y3 with l i n e s
17 %o f c o l o r 4 ( magenta ) and y4 with p o i n t s d i s p l a y e d a s ‘+ ’
multi.m
1. clear all clears variable names and values from the memory
CHAPTER 3. PLOTTING 43
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
3. x = linspace(1,100,100) makes a vector x made up of 100 equally
spaced data points between 1 and 100.
4. y1 = x.2 .0; makes a new vector named y1 having element wise square
of vector x
5. y1 = x.2 .1; makes a new vector named y2 having element wise expo-
nentiation by 2.1 of vector x
6. y2 = x.2 .2; makes a new vector named y3 having element wise expo-
nentiation by 2.2 of vector x
7. y3 = x.2 .3; makes a new vector named y3 having element wise expo-
nentiation by 2.3 of vector x
8. y4 = x.2 .4; makes a new vector named y4 having element wise expo-
nentiation by 2.4 of vector x
Figure 3.3 is obtained by running the code. These types of plots are used
to check the variation of result by varying a particular parameter.
44 CHAPTER 3. PLOTTING
Dr. Sandeep Nagar
sandeep.nagar@gmail.com www.bookmuft.com
10 s u b p l o t ( 2 , 2 , 3 ) , p l o t ( x , y3 )
11 s u b p l o t ( 2 , 2 , 4 ) , p l o t ( x , y4 )
12 %g r i d on
13 %l e g e n d ( ’ x ˆ 2 ’ , ’ x ˆ { 2 . 1 } ’ , ’ x ˆ { 2 . 2 } ’ , ’ x ˆ { 2 . 3 } ’ ) ;
14 %x l a b e l ( ’ x−a x i s ’ )
15 %y l a b e l ( ’ y−a x i s ’ )
16 %t i t l e ( ’ M u l t i p l e Graphs ’ )
17
18 %p l o t y with p o i n t s o f type 2 ( d i s p l a y e d a s ‘+ ’)
19 %and c o l o r 1 ( r e d ) , y2 with l i n e s , y3 with l i n e s
20 %o f c o l o r 4 ( magenta ) and y4 with p o i n t s d i s p l a y e d a s ‘+ ’
multiSubplot.m
As seen in figure 3.4, plots are organized as matrix where row number
as well as column number dictates its position. Index of the plot can then
be used to treat it as an object for further processing on graphical object.
CHAPTER 3. PLOTTING 45
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
Many commands for controlling the font size, tick labels, fonts, inserting
mathematical equations etc. can be known by writing help plot or reading
the documentation of this function. Ample of examples can be obtained from
the web. This function will be used frequently, so its is necessary that one
has good command over its use.
3.1.2 3D plots
There are various functions available for 3D plotting in octave. Choosing
one of them depends on particular problem.
mesh
1 a = b = l i n s p a c e ( −8 , 8 , 4 1 ) ’ ;
2 [ xx , yy ] = meshgrid ( a , b ) ;
3 c = s q r t ( xx . ˆ 2 + yy . ˆ 2 ) + e p s ;
4 d = sin (c ) ./ c ;
5 mesh ( a , b , d ) ;
ThreeDMesh.m
Two variables are created namely a and b and they store linearly spaced
41 data points between −8 to 8, as a row vector. These two row vectors
(both 1X41 in dimension) are passed as arguments for the fucntion meshgrid
which gives two outputs: xx and yy. These are 41X41 dimensioned matrices
where rows of xx are copies of a and columns of yy are copies of b. meshgrid
can also take third argument whose copes make a complete 3D grid. Oth-
erwise on this two dimensional base grid, a function can be defined for data
points defined by copies of a and b vector. In our case the function is defined
as:
p
c= x2 + y 2 (3.1)
and
46 CHAPTER 3. PLOTTING
Dr. Sandeep Nagar
sandeep.nagar@gmail.com www.bookmuft.com
sin(c)
d= (3.2)
c
Note: Function eps produces a very small number (2.2204.10−16 for
machine used test at the time of writing the book). It is widely used in
numerical computation where zero needs to be avoided especially the case
of division by zero. By adding a very small number to large numbers, we
avoid this problem (remember that variable c calculated in 3 is then used
under division as a denominator in step 4).
Continuing now the plotting exercise, new arrays can then be used to
plot by applying a 3D plotting function mesh() which takes these two arrays
a and d as its arguments resulting in figure 3.5. If mesh(x,y,z) is used then
a wire-frame mesh made up of rectangles. The vertices of the rectangles are
made of data points generated by the function (in our case equation. 3.1 and
eq. 3.2). The (x, y) coordinated of vertices are given by xx and yy matrices
since x coordinated comes from xx matrix and y coordinate comes from yy
matrix. z determines the height above the plane of each vertex. In this way
CHAPTER 3. PLOTTING 47
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
a 3D plot is plotted. It is important to note that the original 3D ”curve”
is interpreted as a surface made of flat ”rectangles” which is at best an ap-
proximation. In some cases, this error can be ignored. To get less error, size
of rectangles can be made small, if possible. There are some other variations
of the same function like ezmesh, meshc, meshz. A simple help command
can be very useful to judge which one will suit best for a particular problem.
The mesh also codes color for height (z-value). This is computed by
linearly scaling the Z values to fit the range of the current color-map (write
help colormap to know more).
meshc
meshc() generates a 3D rectangulated mesh as well a contour at base. As
seen in figure 3.6, apart from producing a 3D plot for given function, one
also obtains a contour plot. Please note that this time, the equation working
on matrices, is written as an argument of meshc() function, this making the
programs even smaller.
1 x=l i n s p a c e ( − 1 0 , 1 0 , 5 0 ) ;
2 y=l i n s p a c e ( − 1 0 , 1 0 , 5 0 ) ;
3 [ xx , yy]= meshgrid ( x , y ) ;
4 meshc ( xx , yy ,2 −( xx .ˆ2+ yy . ˆ 2 ) )
ThreeDMeshc.m
surf()
surf() generates a surface plot where wire-mesh is simply filled up at empty
points, as seen in figure 3.7,
1 a = b = l i n s p a c e ( −8 , 8 , 1 0 ) ’ ;
2 [ xx , yy ] = meshgrid ( a , b ) ;
3 c = s q r t ( xx . ˆ 2 + yy . ˆ 2 ) + e p s ;
4 d = sin (c ) ./ c ;
5 surf (c , d) ;
ThreeDsurf.m
3.2 Summary
A rich library of plotting functions makes octave a suitable choice for plotting
data in a variety of publication-ready formats. Together with commands to
48 CHAPTER 3. PLOTTING
Dr. Sandeep Nagar
sandeep.nagar@gmail.com www.bookmuft.com
access systems files and folders, these plots can be directed to be saved at
appropriate places for making a suitable report. Plotting in 3D and viewing
with different angles is quite intuitive in octave. Hence octave presents a
suitable choice to visualize the data.
CHAPTER 3. PLOTTING 49
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
50 CHAPTER 3. PLOTTING
Data through File reading and writing
4
4.1 Introduction
Using the information in chapter on arrays and chapter on plotting, one can
now formulate physical problems in terms of numerical computations and
solve them on digital computer. This process has some requirements such
as:
• Computer program should be able to read the file and make array
without errors. If errors have been made, then a mechanism to check
those errors and giving a warning to the user should be in place. If
possible correcting them should also be in place.
51
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
• If a report for particular experiment having input parameters, process-
ing data and output as file or graph, can be generated, then it makes
the task of user easier.
Octave has some features for each of these steps. Present chapter will
discuss them in brief.
4.2.1 Users
A computing system is accessed by different users. Each user defines a
workspace to avoid damaging each other’s work. After login, a user’s workspace
becomes active for a user. Workspace is made up of various files and folders.
Some files are essential for the OS to define the workspace and its properties,
hence they should not be altered at each time. This is ensured by giving
permissions for various users. ”Reading” and ”Writing” a file is restricted
by permissions. ”Administrator” (fondly called admin) is also called ”super
user” who has all the privileges of having all permissions to edit any file/-
folder. One must understand the defined user-type for on computer system
and then issue commands accordingly. If one is not permitted to access cer-
tain folders and input data is placed inside those files/folders, then unless
one seeks to change the permission from the admin, one would always get
an error.
Under the user, /home directory, contains another directory named /sandeep.
This is the present working space. When pwd is typed on the terminal, a
variable name named ans stores this data (file path). A variable name of
choice, can be assigned to store the filename as a string.
Multiple variables can be stored in the same file by passing the name of
variables at the time of saving.
help save and help load gives very useful instructions about using
them. Using ”options” one can save the file in a specific format. For exam-
ple, at line number 26, all variables names starting with ”m” are saved as
binary data inside a binary file named ”SavedAsBinary”. This is particu-
larly important for the case were data generated from octave based numerical
computation is used to feed another software. One can also specify precision
of saved data using options. Also one can compresses a big file using -zip
command. This is very useful in case the data generated by octave is large
in size and needs to be transmitted.
load function follows the same logic as save function. Data can be
unzipped and loaded from a particular formatted file as an array. Array
thus populated, can be used for computation and resultant files can be made
using save function again (if required). Elaborate computations require this
procedure to be repeated successively many times, thus the functions have
been optimized to locate and load required data in a short time.
diary
An octave session can be recorded in a file by using the command diary.
Using help diary its use can be obtained. Writing help "filename" al-
lows recording the session at a file with given filename. The commands and
their outputs are continuously updated using this function.
Once all data has been read from or written to the opened file it should
be closed. The fclose function does this.
1 MyFile = f o p e n ( ” a . dat ” , ” r ” ) ;
Functions csvread and csvwrite are used to read data from .csv filed which
stand for comma seperated values.
Suppose the following data needs to be stored as a csv file.
1 2 3 4
5 6 7 8
8 7 6 5
4 3 2 1
Following code makes an array using csvwrite to create a file named
csvTestData.dat containing the matrix values. One can check by simply
opening this newly created file in a text editor. At line number 3, a new
file named csvTestData1.dat is created with offset defined at row 1 and
column 2.
1 >> a = [ 1 , 2 , 3 , 4 ; 5 , 6 , 7 , 8 ; 8 , 7 , 6 , 5 ; 4 , 3 , 2 , 1 ] ;
2 >> a
3 a =
4
5 1 2 3 4
6 5 6 7 8
7 8 7 6 5
8 4 3 2 1
9 >> c s v w r i t e ( ’ csvTestData . dat ’ , a )
10 >> c s v w r i t e ( ’ csvTestData1 . dat ’ , a , 1 , 2 )
11 >> a1 = c s v r e a d ( ’ csvTestData . dat ’ )
12 a1 =
13
14 1 2 3 4
15 5 6 7 8
16 8 7 6 5
17 4 3 2 1
18
19 >> a1 = c s v r e a d ( ’ csvTestData . dat ’ , 1 , 2 )
20 a1 =
21
22 7 8
23 6 5
24 2 1
25
26 >>
Now csvread function can be used to create matrices with desired offsets
just as the function csvwrite.
Once the module has been automatically installed at a proper place, its
functions can be used. Following is the list of file extensions and associated
permissions.
1 File extension COM POI POI/OOXML JXL OXS UNO OTK JOD OCT
2 −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
3 . x l s ( Excel95 ) R R R
4 . x l s ( Excel97 −2003) + + + + + +
5 . x l s x ( E x c e l 2 0 0 7 +) ˜ + (+) + +
6 . x l s b , . xlsm ˜ ? R R?
7 . wk1 + R
8 . wks + R
9 . dbf + +
10 . ods ˜ + + + +
11 . sxc + +
12 . fods +
13 . uos +
14 . dif + +
15 . csv + R
16 . gnumeric +
17 −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
18
19 R : only read ; + : f u l l r e a d / w r i t e ; ˜ : dependent on E x c e l
version
• xlsopen(’Filename.xls’)
• xlsclose
1 >> pkg l o a d i o
2 >> a = rand ( 1 0 , 1 0 ) ;
3 >> o d s w r i t e ( ’ a . ods ’ , a )
4 ans = 1
5 >> l s
6 a . ods
Here a variable named a stores the data from the data file stored at http:
//www.fs.fed.us/land/wfas/fdr_obs.dat. Alternatively, the whole data
is stored as a file named a.dat using the function urlwrite(URL).
4.4.1 print
print command handles the printing jobs such as printing using a printer
and/or plotter, printing to a file etc. Especially for figures, this command is
very useful to save a figure automatically by a desired filename in a specified
format.
1 % Sa vin g i n svg format
2 figure (1) ;
3 c l f () ;
4 peaks ( ) ;
clf function clears the current graphic window. A lot of other ”options”
for saving in different formats exist for print command. To know more,
please type help print at octave terminal.
4.4.2 saveas
saveas functions saves a graphic object in a desired format as follows:
1 c l f () ;
2 a = sombrero ( ) ;
3 s a v e a s ( a , ” f i g u r e 3 . png” ) ;
4.4.3 orient
orient(a,orientation) function defines the orientation of an graphical
object ”a”. The valid values for orientation parameters are portrait,
landscape, and tall.The landscape option changes the orientation so the
plot width is larger than the plot height. The tall option sets the orienta-
tion to portrait and fills the page with the plot, while leaving a 0.25 inch
border. The portrait option (default) changes the orientation so the plot
height is larger than the plot width.
4.5 Summary
In present chapter, various functions enabling reading and writing permis-
sion as well as taking data to and from a file, has been illustrated. This
becomes an essential part of a numerical computation exercise. The data
63
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
5.2 Loops
Loops form an essential part of an algorithm since they perform the tasks
which computers perform best: doing repetitive actions in a very fast man-
ner. Loops can come in many flavors like for loop which repeats certain
tasks over a list of variable values, while loop which checks a logical con-
dition before executing certain task and if-then-else loop which checks
a condition and directs the flow of algorithm. Choice of a particular loop
depends on the problem at hand.
5.2.1 while
while loop defines a logical condition and until it is satisfied, it run a block
of code. The syntax for while loop is:
1 while condition
2 BODY
3 endwhile
Here the keyword while initiates the execution of a while loop. The
condition is a logical condition whose answer can be ’true’ (1) or ’false’
(0). The BODY encompasses the st of commands which is executed until the
condition holds true.
1 x = 1.0;
2 w h i l e x < 10
3 disp ( sqrt (x) ) ;
4 x = x+1;
5 endwhile
while1.m
The program while1.m runs by first initializing a variable x to value 1.0.
Then it lists a logical condition:
x < 10
.
At the first step of loop, x = 1, this condition is satisfied since 1 < 10.
When this condition is satisfied, disp(sqrt(x)) is executed which displays
5.2.2 do-until
It is important to note that there can be cases where the body of a loop
might not get executed even one in the case of while loop. This is the case
when after initialization, condition is not satisfied. To overcome this kind
of scenario do-until loop is framed whose syntax is as follows:
1 do
2 BODY
3 until condition
The loop first executes the body of code and then check for condition.
This way, the code block comprising the BODY of loop is at least executed
once. The usage can be understood in the example below:
1 % Displaying square root of
2 % f i r s t t e n p o s i t i v e n a t u r a l numbers
3
4 x = 1.0;
5 do
6 disp ( sqrt (x) ) ;
7 x = x+1;
8 u n t i l x == 10
dountil1.m
5.2.3 for
for loop is used to perform computation on a list of known values. The
syntax of for loop is:
The keyword for declared the starting of loop where a variable takes the
values stored in a vector. Then a body of code (here represented by BODY)
is executed. The keyword end declares end of for loop. This is explained
in the example below:
1 % program t o c a l c u l a t e s q u a t e r o o t
2 % o f f i r s t 10 numbers
3
4 for i = 1:10
5 ans = s q r t ( i )
6 end
for1.m
5.2.4 if-elseif-else
Situation where a number of conditions needs to be checked at different
points of times, if-elseif-else loop works well. The syntax for the loop
is given by:
1 i f condition1
2 BODY1
3 e l s e i f condition2
4 BODY2
5 else
6 BODY3
7 endif
ifelse1.m
5.3 Functions
Function is a set of code which can be called as and when required. Hence
it can be defined separately either in a separate file or within the body of
program. Octave presents some ways to define a functions as discussed in
following subsections.
5.3.1 function
The definition of a function follows the syntax:
1 f u n c t i o n [ r e t u r n v a l u e 1 , r e t u r n v a l u e 2 , . . . ] = name ( [ arg1 ,
arg2 , . . . ] )
2 body
3 endfunction
Hence one can see that function named fn1 is performing the computa-
tion x2 − y 2 on the two input arguments for which it is defined.
help NaN and help prod gives useful insights into the behavior of these
commands.
5.3.2 inline
Functions can also be defined inline using the command inline as follows:
1 >> f = i n l i n e ( ”xˆ2+y” ) ;
2 >> f ( 1 , 2 )
For example:
1 >> a = @( x ) s i n ( x ) ∗ c o s ( x ) ;
2 >> quad ( a , 0 , 1 )
3 ans = 0 . 3 5 4 0 4
4 >> quad ( a , 0 , p i )
5 ans = 7 . 3 0 3 1 e −017
6 >> quad ( a , −pi , p i )
7 ans = 0
8 >> quad ( a , −pi , 2∗ p i )
9 ans = −2.8435 e −016
10 >> quad ( a , −2∗pi , 2∗ p i )
11 ans = 0
help quad tells us that the function quad evaluated the integration of a
function between two values. Hence line 1 defines a function sin(x)cos(x)
whose integration.
Z 1
sin(x)cos(x) = 0.35404
0
Z π
sin(x)cos(x) = 7.3031 × 10−17
0
Z π
sin(x)cos(x) = 0
−π
Z 2π
sin(x)cos(x) = −2.8435 × 10−16
−π
Z 2π
sin(x)cos(x) = 0
−2π
Hence using anonymous function definition, one need not name a func-
tion.
5.4 Summary
Defining functions is the key to modular programming. Octave presents an
elegant way to define and use functions both inline and in separate files.
When combined with the ability to write functions inside a loop, complex
problems can be implemented in few lines of codes. It requires an artistic
attitude while designing an algorithm where functions and loops are the
paintbrush to devise an elegant solutions to a given numerical problem.
73
Dr. Sandeep Nagar
www.bookmuft.com sandeep.nagar@gmail.com
putation. Defining a problem in proper term is just the first step. Making
the right model and then using the right method to solve (solver) enables
to distinguish between a naive and experienced scientist/engineer.
3x + 4y + 9z = 10
This is an equation having a term 3x + 4y + 9z on left hand side (LHS)
and a term 10 on right hand side (RHS). Please note that whereas LHS is
an algebraic term, RHS is a number.
In real life we can have situations which can be mixture of these scenar-
ios. Like an object can oscillate and move in curved fashion at the same
time. In that case we write an expression using mixture of functions or find
new functions which could explain the behavior of object. Verifying the
functions is done by finding solutions to equations describing the behavior
and matching it with observations taken on object. If they match perfectly,
we obtain perfect solutions. In most cases, an exact solutions might be dif-
ficult to obtain. In these cases, we get an ”approximate” solution. If the
errors involved while obtaining an approximate solution are within tolera-
tion limits, the models can be acceptable.
−x + 3y = 4 (6.1)
2x − 4y = −3 (6.2)
For example, Newtons second law of motion says that rate of change
of velocity of an object is directly proportional to the force applied on it.
Mathematically:
dy
F ∝ (6.3)
dx
The proportionality is turned into equality by substituting for a constant
of multiplication m such that:
dy
F =m× (6.4)
dx
If we know values or expressions for F , this equation can be solved ana-
lytically and solutions can be found to this equation. But in some cases, the
analytical solution may be too difficult to obtain. In those cases, we digitize
the system and find a numerical solution.
There are many methods to digitize and numerically solve a given func-
tion. Programs to implement a particular method to solve a function nu-
merically, is called a solver. A lot of solvers exist to solve a function. Choice
of solver is critical to successfully obtain a solution. For example, equation
6.4 is a differential equation. It is a first order ordinary differential equation.
A number of solvers exist to solve it like Euler, Runge-Kutta etc. Choice
of particular solver depends on accuracy of its solution, time taken for ob-
taining a solution and amount of memory used during the process. The
latter is important where memory is not an freely expendable commodity
6.5 Summary
Almost all branch of science and engineering requires one to perform numer-
ical computation. Octave is one of the alternative to do so. Octave has a
library of optimized functions for general computation. Also it has a variety
of packages are present to perform a specialized job. This makes it an ideal
choice for prototyping a numerical computation problem efficiently.