You are on page 1of 74

Introduction

to
Octave

MANAV RACHNA UNIVERSITY


Outline:
 What is Octave?

 Variables, array, matrix

 Operators (Arithmetic, relational, logical )

 Display Facilities

 Using operators

 Creating Plots
MANAV RACHNA UNIVERSITY
What is Octave?
 Octave is basically a high level language which has many
specialized toolboxes for making things easier for us.
 Octave is compatible with MATLAB.
 Octave is free software
 Octave provides a language and environment for
numerical computation, data analysis, visualisation and
algorithm development.

MANAV RACHNA UNIVERSITY


 Octave provides functions that operate on
 Integer, real and complex numbers

 Vectors and matrices

 Structures

MANAV RACHNA UNIVERSITY 4


What are we interested in?
 Octave is a high-level language, primarily intended for
numerical computations.

 During the session, we will cover the following topics


• Basic calculations and operation
• Plotting
• Differentiation & Integration(Applications)
• Matrices

MANAV RACHNA UNIVERSITY


Octave Screen
 File Browsing
 View files and m-files
 Workspace
 Stores the variable name , values
& their types
 View program variables
 Command Window
 type commands
 Command History
view past command
 Documentation Window
Read Document & seek help

MANAV RACHNA UNIVERSITY


Variables
 No need for types. i.e.,
int a;
double b;
float c;
 All variables are created with double precision unless
specified and they are matrices.
Example:
>>x=5;
>>x1=2;

 After these statements, the variables are 1x1 matrices


with double precision
MANAV RACHNA UNIVERSITY
The Octave Interface
 Pressing the up arrow in the command window will
bring up the last command entered.
 This saves you time when things go wrong.

 If you want to bring up a command from some time


in the past type the first letter and press the up
arrow.

MANAV RACHNA UNIVERSITY 8


Using Ocatve as a calculator

 Let’s start at the very beginning. For example,


suppose we want to calculate the expression, 1 + 2 ×
3. We type it at the prompt command (>>) as follows
 >> 1+2*3
 ans = 7

MANAV RACHNA UNIVERSITY


Using Octave as a calculator
 We will have noticed that if We do not specify an
output variable, Octave uses a default variable ans,
short for answer, to store the results of the current
calculation. Note that the variable ans is created (or
overwritten, if it is already existed). To avoid this, we
may assign a value to a variable or output argument
name. For example,
 >> x = 1+4*3
 x = 13

MANAV RACHNA UNIVERSITY


Using Octave as a calculator

 Will result in x being given the value 1 + 2 × 3 = 7.


This variable name can always be used to refer to the
results of the previous computations. Therefore,
computing 4x will result in
 >> 4*x
 ans = 28.0000

MANAV RACHNA UNIVERSITY


Creating Octave variables
 The syntax of variable assignment is
variable name = A value (or an expression)
 For example:

>> A=32
A=32
 To find out the value of a variable simply type the

name in
 >> A
A=32

MANAV RACHNA UNIVERSITY


Creating Octave variables
 To make another variable equal to one already entered
 >> B = A

 The new variable is not updated as you change the

original value
 Example:

 >> B=A

B= 32
 >> A=15

A=15
>> B=32
MANAV RACHNA UNIVERSITY
Creating Octave variables

 The value of two variables can be added together, and


the result displayed…
 >> A = 10
 >> A + A
 …or the result can be stored in another variable
 >> A = 10
 >> B = A + A

MANAV RACHNA UNIVERSITY


Creating Octave variables

 For Example:
 >> A=10
 A=10
 >> A+A
 ans = 20
 >> B=A+A
 B=20 

MANAV RACHNA UNIVERSITY


Basic arithmetic operators

 Symbol Operation Example


 + Addition 2+3
 ∗ Multiplication 2∗3
 − Subtraction 2–3
 / Division 2/3

MANAV RACHNA UNIVERSITY


Variables
 Variables needs to be declared.
 Variable names can contain up to 63 characters.
 Variable names must start with a letter followed by
letters, digits, and underscores.
 Variable names are case sensitive.

MANAV RACHNA UNIVERSITY


Octave Special Variables
 ans Default variable name for results
 pi Value of π
 eps Smallest incremental number
 inf Infinity
 NaN Not a number e.g. 0/0

MANAV RACHNA UNIVERSITY


Overwriting variable

 Once a variable has been created, it can be


reassigned. In addition, if you do not wish to see the
intermediate results, you can suppress the numerical
output by putting a semicolon (;) at the end of the
line. Then the sequence of commands looks like this:
 >> t = 5;
 >> t = t+1
 t=6

MANAV RACHNA UNIVERSITY


Error messages

 If we enter an expression incorrectly, Octave will


return an error message. For example, in the
following, we left out the multiplication sign, *, in
the following expression
 >> x = 10;
 >> 5x
 ??? 5x |
 Parse Error: Syntax error.

MANAV RACHNA UNIVERSITY


Making corrections

 A previously typed command can be recalled with the


up-arrow key ↑. When the command is displayed at
the command prompt, it can be modified if needed
and executed.

MANAV RACHNA UNIVERSITY


Controlling the hierarchy of
operations
 Let’s consider the arithmetic operation, but now we

will include parentheses. For example, 1 + 2 × 3 will


become (1 + 2) × 3
 >> (1+2)*3
 ans =9
 And, from previous example
 >> 1+2*3
 ans = 7
 By adding parentheses, these two expressions give
different results: 9 and 7.
MANAV RACHNA UNIVERSITY
 The order in which Octave performs arithmetic
operations is exactly that taught in high school
algebra courses.

MANAV RACHNA UNIVERSITY


Hierarchy of arithmetic operations
Precedence Mathematical operations
First The contents of all parentheses are evaluated

first, starting from the innermost parentheses


and working outward.
Second All exponentials are evaluated, working from
left to right.
Third All multiplications and divisions are
evaluated, working from left to right
Fourth All additions and subtractions are evaluated,
starting from left to right
MANAV RACHNA UNIVERSITY
Controlling the appearance of floating
point number
 MATLAB by default displays only 4 decimals in the
result of the calculations, for example −163.6667, as
shown in above examples. However, Octave does
numerical calculations in double precision, which is 15
digits.
 >> format short
 >> x=-163.6667

MANAV RACHNA UNIVERSITY


 If we want to see all 15 digits, we use the command
format long
 >> format long
 >> x= -1.636666666666667e+002
 To return to the standard format, enter format short,
or simply format. There are several other formats. For
more details, see the octave documentation, or type
help format.

MANAV RACHNA UNIVERSITY


Managing the workspace
 It is a good idea to issue a clear command at the start
of each new independent calculation.
 >> clc
 The command clc removes all variables from the
workspace. This frees up system memory. In order to
display a list of the variables currently in the memory,
type
 >> who
 While, who will give more details which include size,
space allocation, and class of the variables.

MANAV RACHNA UNIVERSITY


Entering multiple statements per line
 It is possible to enter multiple statements per line.
 Use commas (,) or semicolons (;) to enter more than
one statement at once.
 Commas (,) allow multiple statements per line without
suppressing output.
 Example
 >> a=7; b=cos (a), c=cosh (a)
 b = 0.6570
 c=
 548.3170
MANAV RACHNA UNIVERSITY
Miscellaneous commands

Here are few additional useful commands:


To clear the Command Window, type clc
To abort a Octave computation, type ctrl-c
To continue a line, type . . .
Getting help Information about any command is

available by typing
>> help Command
Another way to get help is to use the look for command.
MANAV RACHNA UNIVERSITY
 Use on-line help to request info on a specific function
>> help sqrt

 Tab completion
After typing few alphabet press tab to auto complete
it.
 In the current version , the doc function opens the on-
line version of the help manual. This is very helpful
for more complex commands.
>> doc plot

MANAV RACHNA UNIVERSITY


Mathematical functions
 cos(x) Cosine abs(x) Absolute value
sin(x) Sine sign(x) Signum function
tan(x) Tangent max(x) Maximum value
acos(x) Arc cosine min(x) Minimum value
asin(x) Arc sine ceil(x) Round towards +∞
atan(x) Arc tangent floor(x) Round towards −∞
exp(x) Exponential round(x) Round to nearest integer
sqrt(x) Square root rem(x) Remainder after division
log (x) Natural logarithm angle(x) Phase angle
log10(x) Common logarithm conj(x) Complex conjugate
pi π = 3.14159 . . . Inf The infinity, ∞
i,j The imaginary unit i, √ −1
NaN Not a number

MANAV RACHNA UNIVERSITY


Example 1:

MANAV RACHNA UNIVERSITY


Example 2:

 >> log (142)


ans =
4.9558
 >> log10 (142)
ans =
2.1523
 Note the difference between the natural logarithm
log(x) and the decimal logarithm (base 10) log10(x).

MANAV RACHNA UNIVERSITY


 we enter the following commands in Octave,
>> sin (pi/4)
ans =
0.7071
 >> exp (10)
 ans =
2 .2026e+004

MANAV RACHNA UNIVERSITY


Plotting

MANAV RACHNA UNIVERSITY


MANAV RACHNA UNIVERSITY
Note:
 The plot functions have different forms depending on
the input arguments.
 If y is a vector plot(y) produces a piecewise linear
graph of the elements of y versus the index of the
elements of y.
 If we specify two vectors, as mentioned above,
plot(x, y) produces a graph of y versus x.
 For example, to plot the function sin (x) on the
interval [0, 4π], we first create a vector of x values
ranging from 0 to 2π, then compute the sine of these
values, and finally plot the result:

MANAV RACHNA UNIVERSITY


Plotting: Plot the function sin(x)
between 0≤x≤4π
 Create an x-array of 100 samples between 0 and 4π.
>>x=linspace(0,4*pi,100);

 Calculate sin(.) of the x-array


>>y=sin(x);
1

0.8

0.6

 Plot the y-array 0.4

0.2

>>plot(y) -0.2

-0.4

-0.6

-0.8

-1
0 10 20 30 40 50 60 70 80 90 100

MANAV RACHNA UNIVERSITY


Adding titles and axis labels

For x label:
>> xlabel(‘x = 0:4*pi’)
For y label

>> ylabel(‘Sine of x’)


For Title

>> title(‘Sine function’)


Remark: The color of a single curve is, by default, blue,
but other colors are possible.
MANAV RACHNA UNIVERSITY
Sine Function
1

0.8

0.6

0.4

0.2
Sin of x

-0.2

-0.4

-0.6

-0.8

-1
0 10 20 30 40 50 60 70 80 90 100
x = 0:4*pi

MANAV RACHNA UNIVERSITY


 The plot function can be used in different ways:
>> plot(data)
>> plot(x, y)
>> plot(data, ‘r.-’)

 In the last example the line style is defined


Colour: r, b, g, c, k, y etc.
Point style: . + * x o > etc.
Line style: - -- : .-
 Type ‘help plot’ for a full list of the options

MANAV RACHNA UNIVERSITY 41


Symbol Color Symbol Line Style Symbol Marker

k Black − Solid + Plus sign

r Red −− Dashed o Circle

b Blue : Dotted ∗ Asterisk

g Green −. Dash-dot . Point

c Cyan none No line × Cross

m Magenta s Square

y Yellow d Diamond

MANAV RACHNA UNIVERSITY


 A basic plot
1

>> x = [0:0.1:2*pi] 0.8

>> y = sin(x)
0.6

0.4

>> plot(x, y, ‘r.-’) 0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

MANAV RACHNA UNIVERSITY 43


Plot the function e-x/3sin(x) between 0≤x≤4π.
 Create an x-array of 100 samples between 0 and 4π.
>>x=linspace(0,4*pi,100);

 Calculate sin(.) of the x-array


>>y=sin(x);
 Calculate e-x/3 of the x-array
>>y1=exp(-x/3);

 Multiply the arrays y and y1


>>y2=y.*y1;

MANAV RACHNA UNIVERSITY


Plot the function e-x/3sin(x) between 0≤x≤4π
 Multiply the arrays y and y1 correctly
>>y2=y.*y1;
0.7
 Plot the y2-array 0.6

0.5

>>plot(y2) 0.4

0.3

0.2

0.1

-0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100

MANAV RACHNA UNIVERSITY


 Some other functions that are helpful to create plots:

 hold on and hold off


 title

 legend

 axis

 xlabel

 ylabel

MANAV RACHNA UNIVERSITY 46


Plot the functions Sin(x) & 2Sin(x):
>> x = [0:0.1:2*pi]; Sin Plots
>> y = sin(x); 2
sin(x)
>> plot(x, y, 'b*-') 1.5 2*sin(x)

>> hold on 1

>> plot(x, y*2, ‘r.-') 0.5

>> title('Sin Plots'); 0


y

>> legend('sin(x)', '2*sin(x)'); -0.5

>> axis([0 6.2 -2 2])


-1

>> xlabel(‘x’);
-1.5

>> ylabel(‘y’);
-2
0 1 2 3 4 5 6
>> hold off x

MANAV RACHNA UNIVERSITY 47


 >> x=-1:.1:10;
 >> y=sqrt(8*x);
>> plot(x,y)
9

8

 Warning: Imaginary 7

parts of complex X 5

and/or Y arguments
4

ignored 2

0
-2 0 2 4 6 8 10

MANAV RACHNA UNIVERSITY


 >> hold on
 >> y=-sqrt(8*x);
 >> plot(x,y) 10

Warning: Imaginary
8
 6

parts of complex X 4

and/or Y arguments 0

ignored
-2

-4

-6

 >> hold off -8

-10
-2 0 2 4 6 8 10

MANAV RACHNA UNIVERSITY


 fplot(“[sqrt(8*x), -sqrt(8*x)]”, [0, 10])
 You will get the following graph
10

-2

-4

-6

-8

-10
-1 0 1 2 3 4 5 6 7 8 9 10

MANAV RACHNA UNIVERSITY


Clearing Variables
 You can use the command “clear all” to delete all the
variables present in the workspace

 You can also clear specific variables using:


>> clear Variable_Name

MANAV RACHNA UNIVERSITY 51


Differentiation
&
Integration

MANAV RACHNA UNIVERSITY


Differentiation

MANAV RACHNA UNIVERSITY


MANAV RACHNA UNIVERSITY
Integration
 Integration is a mathematical technique which
is use to determine the rate at which function
change
 Limit of a sum
 In octave, command for integration is int(y,x)
where y is the function of x
 >>syms x y
 >>y=cos(x);
 >>int(y,x)
 >>ans = sin(x)
MANAV RACHNA UNIVERSITY
MANAV RACHNA UNIVERSITY
Matrix

MANAV RACHNA UNIVERSITY


Array, Matrix
 Entering a vector: An array of dimension 1 ×n is
called a row vector, whereas an array of
dimension m × 1 is called a column vector. The
elements of vectors in octave are enclosed by
square brackets and are separated by spaces or by
commas. For example, to enter a row vector, x,
type
x = [1 2 5 1]
x =
1 2 5 1

MANAV RACHNA UNIVERSITY


 Column vectors are created in a similar way, however,
semicolon (;) must separate the components of a column
vector,
y = [1; 5; 3]
y =
1
5
3
 Entering a matrix: A matrix can be created in octave as
follows (note the commas AND semicolons):
>> matrix = [1, 2, 3 ; 4 , 5 ,6 ; 7 , 8 , 9]
matrix =
1 2 3
4 5 6
7 8 9

MANAV RACHNA UNIVERSITY


Transpose of a Matrix
On the other hand, a row vector is converted to a
column vector using the transpose operator. The
transpose operation is denoted by an apostrophe or a
single quote (’).
>> z = x’
z=
1
2
5
1

MANAV RACHNA UNIVERSITY


 Thus, x(1) is the first element of vector x, x(2) its
second element, and so forth.
 >>x(1)
ans= 1
>>x(2)
ans=2
 To access blocks of elements, we use octave’s colon
notation (:). For example, to access the first three
elements of x, we write,
 >> x(1:3)
 ans =
 1 2 5
MANAV RACHNA UNIVERSITY
 Or, all elements from the third through the last
elements,
 >> v(3,end)
 ans = 5 1
 where end signifies the last element in the vector. If v
is a vector, writing
 >> v(:)
 produces a column vector, whereas writing
 >> v(1:end)
 produces a row vector.

MANAV RACHNA UNIVERSITY


Matrix Index
 The matrix indices begin from 1 (not 0 (as in C))
 The matrix indices must be positive integer
Given:

A(-2), A(0)

Error: ??? Subscript indices must either be real positive integers or logicals.

A(4,2)
Error: ??? Index exceeds matrix dimensions.

MANAV RACHNA UNIVERSITY


Long Array, Matrix
 Creating a vector with constant spacing by specifying
the first term, the spacing, and the last name.
Variable_name=[m:q:n] or Variable_name = m:q:n
>> t =1:10
t=
1 2 3 4 5 6 7 8 9 10

>>k =2:-0.5:-1
k=
2 1.5 1 0.5 0 -0.5 -1

MANAV RACHNA UNIVERSITY


 B = [1:4; 5:8]
B=
1 2 3 4
5 6 7 8
 Creating a vector with constant spacing by specifying
the first term, and last terms, and the number of terms.
 Variable_name = linspace (xi,xe,n)
>> va = linspace(0,8,6)
Va = 0 16 3.2 4.8 6.4 8

MANAV RACHNA UNIVERSITY


Generating Vectors from functions
 zeros(M,N) MxN matrix of zeros
x = zeros(1,3)
x =
0 0 0

 Eye(M) MxM identity matrix X= eye(3)


1 0 0
0 1 0
 ones(M,N) MxN matrix of ones 0 0 1

x = ones(1,3)
x =
1 1 1

MANAV RACHNA UNIVERSITY


Concatenation of Matrices
 x = [1 2], y = [4 5], z=[ 0 0]

A = [ x y]

1 2 4 5

B = [x ; y]

1 2
4 5

C = [x y ;z]
Error:
??? Error using ==> vertcat CAT arguments dimensions are not consistent.

MANAV RACHNA UNIVERSITY


Operators (arithmetic)
+ addition
- subtraction
* multiplication
/ division
^ power
‘ complex conjugate transpose

MANAV RACHNA UNIVERSITY


Matrices Operations

Given A and B:

Addition Subtraction Product Transpose

MANAV RACHNA UNIVERSITY


Operators (Element by Element)

.* element-by-element multiplication
./ element-by-element division
.^ element-by-element power

MANAV RACHNA UNIVERSITY


The use of “.” – “Element” Operation
A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 -1

b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1

K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.

MANAV RACHNA UNIVERSITY


Some matrix functions in Octave
X = ones(r,c) % Creates matrix full with ones
X = zeros(r,c) % Creates matrix full with zeros
A = diag(x) % Creates squared matrix with
vector x in diagonal
[r,c] = size(A) % Return dimensions of matrix A
+-*/ % Standard operations
.+ .- .* ./ % Wise addition, substraction,…
v = sum(A) % Vector with sum of columns

MANAV RACHNA UNIVERSITY


Some powerful matrix functions in
Octave
X = A’ % Transposed matrix
X = inv(A) % Inverse matrix squared matrix
X = pinv(A) % Pseudo inverse
X = chol(A) % Cholesky decomp.
d = det(A) % Determinant
[X,D] = eig(A) % Eigenvalues and eigenvectors
[Q,R] = qr(X) % QR decomposition
[U,D,V] = svd(A) % singular value decomp.

MANAV RACHNA UNIVERSITY


Thank You…

MANAV RACHNA UNIVERSITY

You might also like