You are on page 1of 99

. . .

Octave
. & .

, 2010

OCTAVE

. 1 99

. . .


Octave
.
,
lerosapostolos@gmail.com

.
,
aandreatos@gmail.com


,
5 YNE /,

(, 2010).


. , copyright
.
Creative Commons BY-NC-ND.

:
andriana.mykoniati@gmail.com

, 2010

OCTAVE

. 2 99

. . .

1.

OCTAVE.............................................................................................................. 5
OCTAVE ................................................................................................................ 5
OCTAVE ........................................................................................................... 5
OCTAVE; .............................................................................................. 5
. C++; .......................................... 5
2.
................................................................................................................ 6
2.1 OCTAVE (Starting OCTAVE) ...................................................................................... 6
2.2 OCTAVE (OCTAVE as calculator) .................................................................... 7
2.3 (Built-in functions) ............................................................................ 7
3.
OCTAVE (Environment of OCTAVE) ........................................................................ 9
3.1 (Named variables) ................................................................................ 9
3.2 (Numbers and formatting) ...................................................................... 11
3.3 (Number representation and accuracy) ........................................... 12
3.4 (Loading and saving data) ...................................................... 13
3.5 (Repeating previous commands) ................................................ 14
3.6 (Getting help)................................................................................................. 14
3.7 (Cancelling a command) ....................................................................... 14
3.8 (Semicolon and hiding answers) .......................................... 15
4.
(Arrays and Vectors) .................................................................................. 15
4.1 (Building vectors) ................................................................................ 15
4.2 - (The colon notation) ............................................................. 16
4.3 (Displaying large vectors and matrices) ............................. 17
4.4 (Vector creation functions) .................................................... 17
4.5 (Extracting elements from a vector) ............................................... 18
4.6 (Vector maths) .................................................................................. 19
5.
(Plotting graphs) ............................................................................... 20
5.1 (Improving the presentation) ........................................................... 22
5.2 (Multiple graphs) .................................................................................... 23
5.3 (Multiple figures) .............................................................................. 24
5.4 (Manual scaling) ...................................................................................... 25
5.5 (Saving and printing figures) ................................................... 27
6.
OCTAVE : Script (Octave programming I: Script files) ....................................... 27
6.1 script (Creating and editing a script) ................................................ 27
6.2 scripts (Running and debugging scripts) ............................................ 28
6.3 scripts (Remembering previous scripts)................................................................ 29
7.
(Control statements)........................................................................................ 29
7.1 if...else selection................................................................................................................. 30
7.2 switch selection .................................................................................................................. 32
7.3 for loops .......................................................................................................................... 34
7.4 while loops ....................................................................................................................... 36
7.5 do-until ............................................................................................................. 37
7.6 break continue.............................................................................................. 38
7.7 (Accuracy and precision) .......................................................................... 39
8.
: (programming I: Functions) ........................................................... 40
8.1 1: (Example 1: Sine in degrees) ..................................................... 41
8.2 (Creating and using functions) ................................................... 42
8.3 2: (Example 2: Unit step) .................................................................. 43
9.
(Matrices and vectors) ................................................................................ 46
9.1 (Matrix multiplication) ......................................................................... 47
9.2 (The transpose operator) ......................................................................... 48
9.3 (Matrix creation functions) ..................................................... 48
9.4 (Building composite matrices) ..................................................... 50
9.5 (Matrices as tables) ..................................................................... 51
9.6 (Extracting bits of matrices) ........................................................... 51
10.
(Basic matrix functions) ................................................................... 52
11.
Ax = b (Solving Ax = b) ........................................................................... 54
11.1
(Solution when A is invertible) ....................................................... 55
11.2
LU (Gaussian elimination and LU factorization) .................. 55
11.3
(Matrix division and the slash operator) .................. 56
11.4
(Singular matrices and rank) ........................................................... 57
11.5
(Ill-conditioning) ........................................................................................ 58
11.6
: (Over-determined systems: Least squares) ......... 59

1.1
1.2
1.3
1.4

OCTAVE

. 3 99

. . .

11.7

: (Example: Triangulation) ............................................................... 60


(More graphs) ............................................................................ 62
12.1
(Putting several graphs in one window) ....................... 62
12.2
(3D plots) ............................................................................... 63
12.3
(Changing the viewpoint) .............................................................. 64
12.4
(Plotting surfaces) ....................................................................... 65
12.5
(Images and Movies)............................................................ 66
13.
(Eigenvectors and the Singular Value Decomposition)..... 66
13.1
eig (The eig function) ..................................................................................... 66
13.2
(The Singular Value Decomposition) .............................................. 67
13.3
: (Approximating matrices: Changing rank) .................................. 69
13.4
svd (The svd function) .......................................................................................... 69
13.5
svd (Economy SVD) ............................................................................................. 70
14.
(Complex numbers)....................................................................................... 71
14.1
(Plotting complex numbers) ............................................... 73
14.2
(Finding roots of polynomials) ....................................................... 74
15.
(Polynomial manipulation) ........................................................................ 74
15.1
(Finding Roots)....................................................................................... 75
15.2
compan (c) .................................................................................................. 76
15.3
...................................................................................... 76
15.4
............................................................................................. 77
15.5
.............................................................. 77
15.6
(curve fitting) .................................................................................. 78
16.
OCTAVE - .............................................................. 79
16.1
.......................................................................................... 81
16.2
......................................................................................... 82
16.3
.......................................................................................... 83
16.4
............................................................................... 83
17.
OCTAVE ........................................................... 85
17.1
(Convolution and Filtering) ................................................................. 85
17.2
(Filters and Transfer Functions)............................................... 86
17.3
filter (Function filter) ......................................................................................... 87
17.4
(Impulse Response) ............................................................................... 88
17.5
Fourier (Discrete Fourier Transform) .................................................. 88
18.
......................................................................................... 90
18.1
image .......................................................................... 90
18.2
........................................................................................... 90
18.3
........................................................................................................ 91
18.4
................................................................................................... 93
18.5
........................................................................................... 94
19.
....................................................................................................... 95
19.1
y = f(x) - ............................................ 95
19.2
(plots) ........................................................................................................ 96
19.3
(Miscellaneous commands) .................................................................... 97
(References)................................................................................................................ 99
12.

, .

.
.

OCTAVE

. 4 99

. . .

1.

1.1

OCTAVE

OCTAVE

OCTAVE
.
, , .

. , OCTAVE

. , .
OCTAVE ,

.
OCTAVE
. Dr.
John W. Eaton. GNU General Public License. OCTAVE
MATLAB
. OCTAVE
www.octave.org.

1.2

OCTAVE

OCTAVE ,
.

Mathematica Maple,
. -
. ( )
.

1.3

OCTAVE;

OCTAVE MATLAB ,
, ,
.

.

1.4

.
C++;

C++
. ,
C++
. OCTAVE

OCTAVE

. 5 99

. . .

. C++

OCTAVE,
.

2.

2.1

OCTAVE (Starting OCTAVE)

Synaptics. ,
: Applications > Programming [
Science] > GNU Octave. (
, 3.0.5):

windows, OCTAVE
:
. OCTAVE ,
S t a r t  P r o g r a m s  O c t a v e .

:

OCTAVE

. 6 99

. . .

OCTAVE. >
OCTAVE . OCTAVE
, quit exit.

2.2

OCTAVE (OCTAVE as calculator)

OCTAVE ,
. .
, :
1+2

ENTER OCTAVE :
ans = 3
+ - * /, ^
(. 2^3=8). () .
, , ,
, .

2.3

(Built-in functions)

, OCTAVE
. 1.

1:
cos

Cosine of an angle (in radians) -

sin

Sine of an angle (in radians) -

OCTAVE

. 7 99

. . .

1:
tan

Tangent of an angle (in radians) -

exp

Exponential function (ex)

log

Natural logarithm (loge, not log10)

log10

Logarithm to base 10 10

sinh

Hyperbolic sine

cosh

Hyperbolic cosine

tanh

Hyperbolic tangent

acos

Inverse cosine

acosh

Inverse hyperbolic cosine

asin

Inverse sine

asinh

Inverse hyperbolic sine

atan

Inverse tangent

atan2

Two-argument form of inverse tangent

atanh

Inverse hyperbolic tangent

abs

Absolute value

sign

Sign of the number (-1 or +1)

round

Round to the nearest integer

floor

Round down (towards minus infinity) -

ceil

Round up (towards plus infinity) +

fix

Round towards zero 0

rem

Remainder after integer division

C++
(). 1:
exp(1)

ans = 2.7183
, 2.5sin(15o + ln(3.82)),
:
2.5*sin(15*pi/180 + log(3.8^2))


. 1,
exp 1 (. 1=2.7183).
OCTAVE

. 8 99

. . .

ans = 0.52064
:
,
2.5 sin.
( cos) (radians).
/180 . pi
.
log ln.
OCTAVE
.

3.

OCTAVE (Environment of OCTAVE)

, OCTAVE -
(command-line interface)
ENTER.
OCTAVE (interpreted language)
. (compiled
languages) C++, ,
,
.
, .
OCTAVE,
.

3.1

(Named variables)


.
OCTAVE .
, .
deg , :
deg = pi/180

deg = 0.017453
,
. C++.
OCTAVE .
:

OCTAVE

. 9 99

. . .

2.5*sin(15* deg + log(3.8^2))

ans = 0.52064
,
.

.
OCTAVE.
, ,
OCTAVE ans.
:
new = 5*ans

new = 2.6032

5 x 0.52064. OCTAVE (
)2,
3.
,
.

.
,
: a A.
OCTAVE. ans ,
pi, i j -1 (.
14).
OCTAVE
,
OCTAVE. , sin cos ,
.

MATLAB 4 .
OCTAVE IEEE
(64-bit). ans 0.520639040645464 (
15 ).
3

OCTAVE

. 10 99

. . .

,
ENTER.
4
, :
who

*** dynamically linked functions:


dispatch
*** currently compiled functions:
rem
*** local user variables:
deg new
(workspace),
,
. clear
, :
clear name

name.

3.2

(Numbers and formatting)

OCTAVE . format
. , :
format long

OCTAVE (15) ,
. help format
. format long
, deg:
deg

deg = 0.0174532925199433
:
format short
4

MATLAB ( ) ans.

OCTAVE

. 11 99

. . .

OCTAVE .
OCTAVE
(exponential notation). : 25456.4 = 2.54564 x 104,
OCTAVE 2.5456e+004. OCTAVE
.
OCTAVE:
(Complex numbers): . 3+4i, Octave,
14.
Infinity (Inf): .

.
Not a Number (NaN):
. ,
(
NaN).

3.3

(Number representation and accuracy)

OCTAVE, ,
. ( 10), 12.25 :
12.25 = 1x101 +2x100 +2x10-1+5x10-2

( 2) :
1100.01 = 1x23+1x22+0x21+0x20+0x2-1+1x2-2 = 12.25



.

bit,
. :
1 0.2 0.2 0.2 0.2 0.2

ans = 5.5511e-017
, , .
0.2
OCTAVE

. 12 99

. . .

( 0.0011001100). 1/3
10 . OCTAVE (
)
, ,
, .
.
.
.

3.4

(Loading and saving data)

OCTAVE, .
OCTAVE,
. :
save anyname

(workspace)
anyname.mat ( OCTAVE .mat
). OCTAVE
:
load anyname


.
:
save filename var1 var2

, deg,
( !),
:
save degconv deg

degconv.mat.
:
load degconv

OCTAVE

. 13 99

. . .

OCTAVE (text),

.
.

3.5

(Repeating previous commands)

OCTAVE
(
).
,
.
Delete
Backspace .
OCTAVE .
, .

3.6

(Getting help)

OCTAVE,
, OCTAVE .
:
help commandname

,
help sqrt

sqrt is a built-in function


-- Mapping Function: sqrt (X)
Compute the square root of each element of X. If X is negative, a complex result is returned.
To compute the matrix square root, see
*note Linear Algebra::.
See also: realsqrtOverload function
Additional help for built-in functions and operators is available in the on-line version of the manual.
Use the command doc <topic> to search the manual index.
Help and information about Octave is also available on the WWW
at http://www.octave.org and via the help@octave.org mailing list.

3.7

(Cancelling a command)

,
.
:
OCTAVE

. 14 99

. . .

Ctrl-C
( ) .

3.8

(Semicolon and hiding


answers)

(semicolons) ;
,
C++ .
OCTAVE .
, , OCTAVE
. , ,
OCTAVE .
.

4.

(Arrays and Vectors)

.
(arrays). OCTAVE
.
,
, OCTAVE .
, (
).
. (...)
(M) .

4.1

(Building vectors)

.
[]. :
a = [1 2 3]

a=
1

b = [3,2,1]

b=
3

c = [3;5;12]
OCTAVE

. 15 99

. . .

c=
3
5
12
,
. (semicolons) ENTER
.

. :
a = [1 2 3]

a=
1

d = [a 6]

d=
1

4.2

- (The colon notation)


- :, :
e = 2:7

e=
2

- OCTAVE
, ( )
. ,
a:b:c.
:
e = 2:0.3:4

e = 2.0000 2.3000 2.6000 2.9000 3.2000 3.5000 3.8000

OCTAVE

. 16 99

. . .

: ,
, OCTAVE
. ,
.

4.3

(Displaying large vectors


and matrices)

OCTAVE
, . :
v = 1:1000

(spacebar)
q
OCTAVE. b
.
,

. :
more off

, :
more on

4.4

(Vector creation functions)

OCTAVE .
2.
2:

zeros(M,N)

.
n, M = 1, N = n.
(Creates a matrix where every element is zero. For a row vector of
size n, set M = 1, N = n).

ones(M,N)

.
n, M = 1, N = n.
(Creates a matrix where every element is one. For a row vector of
size n, set M = 1, N = n).

linspace(x1, x2,N)

,
x1 x2.
(Creates a vector of N elements, evenly spaced between x1 and
x2).

OCTAVE

. 17 99

. . .

2:
,
10x1 10x2.
(Creates a vector of N elements, logarithmically spaced between
10x1 and 10x2).

logspace(x1, x2,N)

, zeros ones, ,
, ,
.
.

4.5

(Extracting elements from a vector)

()
, C++. :
a=[1:2:6 -1 0]

a=
1

-1

:
a(3)

ans =
5
- (colon)
:
a(3:5)

ans =
5

-1

a(1:2:5)

ans =
1

OCTAVE

. 18 99

. . .

4.6

(Vector maths)

OCTAVE
. C++
,
2, for loop
. OCTAVE (. 7),
OCTAVE .

.
:
a*2

ans =
2

10

-2

.
+ -, .
OCTAVE
(. 9), 5.
, OCTAVE .* ./. :
a1 b1 a1b1

a 2 * b2 = a 2 b 2
a b a b
3 3 3 3

. , - . ,
a, , :
b = [1 2 3 4 5]

a.*b
ans =
1

15

-4

dot
cross .
,
.

OCTAVE

. 19 99

. . .

-- (.^) .
,
, :
b .^ 2
ans =
1

16

25

16

32

2 .^ b
ans =
2

b. 2
b.
-- (+, -, ./, .*, .^)
, () .
.
OCTAVE . ,
60 ,
:
angles = [0:pi/3:2*pi]

angles =
0

1.0472

2.0944

3.1416

4.1888

5.2360

6.2832

y=sin(angles)

y=
0

5.

0.8660

0.8660

0.0000

-0.8660

-0.8660

-0.0000

(Plotting graphs)

OCTAVE
- GNUPLOT6,
MATLAB. plot(x, y), x y

www.gnuplot.org.

OCTAVE

. 20 99

. . .

. ,
,
7.
:
plot(angles, y)

, , 1.
OCTAVE .

1: y = sin(x), 60.

,
60 . ,
y ( ):
angles = linspace(0, 2*pi, 100);
y = sin(angles);
plot(angles, y);

linspace 100
0 2 ( 100 ).
.

. 2 :

, , .

OCTAVE

. 21 99

. . .

2: y = sin(x), 100 0 2.

5.1

(Improving the presentation)


() plot. ,
, :
plot(angles, y, ro)

.
3 ( help plot OCTAVE).
3:
( help plot)
w

white ()

point ()

solid ()

magenta
()

circle ()

dotted ()

cyan ()

x-mark (x-)

-.

red ()

plus ()

dashdot ( )

green ()

star ()

--

dashed

blue ()

square ()

yellow ()

diamond ()

black ()

triangle (down) [
()]

triangle (up) [
()]

<

triangle (left) [
()]

>

triangle (right) [
()]

pentagram ()

hexagram ()

MATLAB

OCTAVE

. 22 99

. . .

title,
xlabel ylabel:
title (Graph of y = sin(x))
xlabel (Angle)
ylabel (Value)
OCTAVE ( )
( ).
replot
.
, :
grid on

3 .
.

3: y = sin(x), .

5.2

(Multiple graphs)


plot, x y . ,
,
:
plot (angles, y,:, angles, cos (angles), -)

OCTAVE

. 23 99

. . .


. legend
:
legend (Sine, Cosine)

.

4.

4: y = sin(x) y = cos(x).

, plot ,
.
(plots) , hold on.
, ( )
plot:
plot (angles, y, :)
hold on
plot (angles, cos (angles), g-)
legend (Sine, Cosine)

,
hold off.

5.3

(Multiple figures)

. :
figure

OCTAVE

. 24 99

. . .

plot .
, :
plot (angles, tan (angles))

(.
5())8. plot ,
:
figure(0)

5.4

(Manual scaling)

plot angles
100 , . ,
/2, ,
( OCTAVE ).


. axis
. axis
(xmin, xmax, ymin, ymax). :
figure(2)
axis ([0 7 -5 5])

5().
() axis .

(a) Default scaling

(b) Manual scaling

5: y = tan(x) default scaling ( 5a) , axis([0 7 -5 5] ( 5b)).

MATLAB figure OCTAVE


plot .
OCTAVE

. 25 99

. . .

OCTAVE GNUPLOT,
,
.
(
9
) 4 .
4: 2D
, (LMB - Left Mouse Button, RMB Right Mouse Button),
. 8.

(Mouse)

LMB

(Annotate the graph.)

RMB

(Mark Zoom region.)

Autoscale and Replot

Toggle Border

Replot (removes annotations)

Toggle grid

Help

Toggle Logscales

Toggle individual axis

Toggle Mouse control

Toggle Ruler

Decrement mousemode

Increment mousemode

Decrement clipboardmode

Increment clipboardmode

Toggle polardistance

Toggle verbose

Toggle graph size ratio

Go to next zoom in the zoom stack

Go to previous zoom in the zoom stack

Unzoom

Escape

Cancel zoom region

MATLAB
.
OCTAVE

. 26 99

. . .

5.5

(Saving and printing figures)

OCTAVE/GNUPLOT .
,
(command line) print . help print
:
print (graph1.eps , -deps)

postscript graph1.eps.
PNG format , :
print (graph1.png, -dpng)

6.

OCTAVE : Script (Octave programming I: Script


files)

,
OCTAVE script.
OCTAVE . script
OCTAVE, ,
. script
,

.
OCTAVE script , .m
( run.m). , M-files.
( run )
OCTAVE script.

6.1

script (Creating and editing a script)

script ( emacs,
notepad), OCTAVE
:
edit
10.
script, script
. , , script run.m, edit run,
.

10

edit
.

OCTAVE

. 27 99

. . .

OCTAVE . ,

( ):
% Script
%
t = linspace (0, 10, 100);
y = abs (sin (t)); % abs
plot (t, y);
title (Rectified Sine Wave);
labelx (t);

% %
OCTAVE. script
,
.
File  Save As
rectsin.m. ,
.

6.2

scripts (Running and debugging scripts)

script, OCTAVE.
script :
rectsin


. , script ,
OCTAVE:
error: labelx undefined near line 6 column 1
error: called from:
error: C:\Users\Apostolos\Desktop\3.3.3_gcc-4.3.0\apl_examples\
rectsin.m at line 6, column 1
script11. OCTAVE
( ) ( ).
6 rectsin.m, labelx. ,
xlabel. ,
, .
.
11

script, , !

OCTAVE

. 28 99

. . .

script
x-, 6.

6: , rectsin.m script.

6.3

scripts (Remembering previous scripts)

script OCTAVE
scripts
. scripts , what
scripts (data files):
what

m-files in current directory /mnt/hda7/Octave/tutorial


rectsin.m
mat-files in current directory /mnt/hda7/Octave/tutorial
OCTAVE scripts.
rectsin script :
help rectsin

% Script
%
OCTAVE M-file script
.
script
.

7.

(Control statements)


. ( )
OCTAVE

. 29 99

. . .

.
.

.
. END.

END . OCTAVE
.

7.1

if...else selection


. if.
if OCTAVE :

if expression
statements
elseif expression
statements
else
statements
end
C++: ()
(expression) ( )
(statements) {}. , end
if .
, if, OCTAVE scripts,
:
a=0; b=2;
if a > b
c=3
else
c=4
end

c=
4
, OCTAVE
end .

OCTAVE

. 30 99

. . .

(logical
expression)
. OCTAVE, : 0
1 :
1==2

ans =
0
pi > exp(1) & sqrt(-1) == i

ans =
1
,
5. C++.
5: Boole (Boolean expressions)

==

equal ()

if x == y

~=

not equal ( )

if x ~= y

greater than ( )

if x > y

greater than or equal ( )

if x >= y

less than ( )

if x < y

less than or equal ( )

if x <= y

&

AND ()

if x == 1 & y > 2

OR ()

if x == 1 | y > 2

NOT (, )

x = ~y

>
>=
<
<=

1: x.
:
if x > 0
y = log(x);
elseif x < 0
y = log(-x);
else
OCTAVE

. 31 99

. . .

disp("Cannot take the log of zero.");


endif

2: .
:
x = input("Enter a number: ");
x =5;
if x > 0
disp("The number is positive.");
endif
3: .
:
x = input("Enter a number: ");
if x < 0
disp("The number is negative.");
endif
4: .
:
x = input("Enter a number: ");
if x == 0
disp("The number is zero.");
endif

7.2

switch selection

if/elseif
, switch.
:

switch x
case x1 ,
statements
case x2 ,
statements
otherwise,
statements
end
OCTAVE

. 32 99

. . .

switch x (case)
.
C++ break
, OCTAVE
. , otherwise .
:
a=1;

switch a
case 0
disp(a is zero);
case 1
disp(a is one);
otherwise
disp(a is not a binary digit);
end

a is one
disp .
, , .,
disp(a) a.
1: switch
, .
:
city = input (Enter destination city: , s)
switch city
case Rome
disp(100 Euros)
case London
disp(150 Euros)
case Moscow
disp(120 Euros)
otherwise
sprintf(No flights for %s, city)
endswitch

OCTAVE

. 33 99

. . .

7.3

for loops

for,
. OCTAVE
for loop, ,
for loop 40 12. , for loop
. :

for variable = vector


statements
end
vector . vector
- (:),
5 n:
for n=1:5
nf(n) = factorial(n);
end
disp(nf)

24

120

(;) for loop.


o OCTAVE nf(n)
, ( ).
1: j +2 j=1, 2, 3, 4, 5.
:
for j=1:5
J+2
end

ans
ans
ans
ans

=
=
=
=

3
4
5
6

12

for loops , OCTAVE


/.
,
. ,
MMX Intel Pentium 1995,
, Matrix Maths eXtentions.

OCTAVE

. 34 99

. . .

ans = 7
2: x=[1, 2, 3, 4, 5].
:
for j=1:5
x(J) = j^2;
end
x

x = [1 4 9 16 25]
3: x=[1, 2, 3, 4, 5].
:
for j=1:5
x(J) = j^2;
end
x

x = [1 4 9 16 25]
5

4:

(i + 1) .
i

i =1

:
sum=0;
for i=1:5
sum = sum + (i +1)^i;
end
sum

sum =8476
6

5:

(x

xi )

xi , i = 1,...,6

i =1,i 3

( xi = 0.2(i 1),
:

OCTAVE

[0,

1]

i = 1,...,6 ).

. 35 99

. . .

x = (0:5)/5
product=1;
for i=1:2, product = product * (x(3) x(i)); end
for i=4:6, product = product * (x(3) x(i)); end

product

product = - 0.0038400

1 n
6: x = xi .
n i =1
:
x = [1 2 3 4 5]
x_mean = 0;
for entry = x, x_mean = x_mean + entry; endfor
x_mean = x_mean / length(x)

x_mean

x_mean = 3

7.4

while loops


, OCTAVE while loop:

while expression
statements
end
:
x=1;
while 1+x > 1
x = x/2;
end
x

x = 1.1102e-016
OCTAVE

. 36 99

. . .

1: fib 10
Fibonacci.
:
fib = ones (1, 10);
i = 3;
while (i <= 10)
fib (i) = fib (i-1) + fib (i-2);
i++;
end
fib

fib = 1 1

13

21

34

55

2: fib 10
Fibonacci.
:
x = 1.0;
while x < 10
x = x*2;
disp(x);
endwhile
end
2
4
x

x=4

7.5

do-until

do-until while,

, .
if , do-until
, .
do-until ,
(non-empty) .
do-until Octave :

do
OCTAVE

. 37 99

. . .

body
until (condition)
body ()
, condition ()
.
fib 10
Fibonacci.
fib = ones (1, 10);
i = 2;
do
i++;
fib (i) = fib (i-1) + fib (i-2);
until (i == 10)
fib

fib = 1 1

7.6

13

21

34

55

break continue


for
. break continue.
break.
total = 0;
while true
x = input('Value to add (enter 0 to stop): ');
if x == 0
break;
endif
total = total + x;
disp(['Total: ', num2str(total)]);
endwhile

break,
while true. break end
( endwhile). The break statement can be used in any loop: for,
while or do...until.
OCTAVE

. 38 99

. . .

continue
.
for loop, for (
) loop ;
while loop,
(true);
do...until loop,
(false).
,
1 0.
N = 5;
A = zeros(N); % Create an N x N matrix filled with 0s
for row = 1:N
for column = 1:N
if column > row
continue;
endif
A(row, column) = 1;
endfor
endfor
disp(A);
: for (continues) 1
A .

7.7

(Accuracy and precision)

:
x=1;
while 1+x > 1
x = x/2;
end
x

x = 1.1102e-016
while loop x
x 1 , x
OCTAVE

. 39 99

. . .

OCTAVE, x 10-16.
OCTAVE (
13
OCTAVE 2.2251x10-308) .

OCTAVE .
:

a = 13901 = 1.3901 104


b = 0.0012 = 1.2 103
5
(significant figures) ( 10k), a b
. ,
, :

a + b = 13901.0012 = 1.39010012 104


= 1.3901 104 5
, ,
, .
while loop . OCTAVE (
) 15 ,
1x10-16 1,

1.
,
.
,
.

.

8.

: (programming I: Functions)

scripts OCTAVE ,
13

realmax realmin
. eps
1.0
, .
eps 2.2204x10-16 . , x
, 1+x ,
.

OCTAVE

. 40 99

. . .

scripts .
OCTAVE
scripts.
OCTAVE , .
14
, OCTAVE . ,
OCTAVE ,
.
(function) , scripts,
:

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


M-file,
.
, sind()
sind.m.
.
,
.
, , ,
.

8.1

1: (Example 1: Sine in degrees)

OCTAVE ,
. OCTAVE
d
sin(d/180*pi), deg=pi/180 (
3.1), sin(d*deg).
sin(d) ( ),
.
sind.m :
function s = sind(x)
% SIND(X) Calculates sine(x) in degrees
s = sin(x*pi/180);
14

,
, .
, C++,
. C++
. OCTAVE
, .

OCTAVE

. 41 99

. . .

,
. :


1: OCTAVE script.
sind x.
s. s
sind .

2: . scripts,
.
help sind.
OCTAVE .

3: .
x s,
.

(End of the function): OCTAVE


return (
return OCTAVE ).
M-file, OCTAVE
. s
.

8.2

(Creating and using functions)

(editor) ( edit
) .
sind.m.
, .m.

OCTAVE. :
help sind

SIND(X) Calculates sine(x) in degrees


OCTAVE help
.
:
sind(0)

ans =
OCTAVE

. 42 99

. . .

0
sind(45)

ans =
0.70711
t = sind([30 60 90])

t=
0.50000

0.86603

1.00000

.
sind , x
, sin
, .

8.3

2: (Example 2: Unit step)

,
:

0, if t < t0
y=
1, otherwise
:
, t0, . :
function y = ustep(t, t0)
%USTEP(t, t0) unit step at t0
% A unit step is defined as
% 0 for t < t0
% 1 for t >= t0
[m, n] = size(t);
% Check that this is a vector, not a matrix i.e. (1 x n) or (m x 1)
if m ~= 1 & n ~=1
error(T must be a vector);
end
y = zeros(m, n); %Initialise output array
for k = 1:length(t)
if t(k) >= t0
y(k) = 1; %Otherwise, leave it at zero, which is correct
end
OCTAVE

. 43 99

. . .

end

1: ustep,
, t t0.
, y.

2-5: .
.

6: ustep, t, ,
.
size , :
( ).
OCTAVE ,
.
, .

7-10: t . t .
(
). error
.

11: ,
.
t, .

12: t, y.
for loop . length
t.

13-15: , t<t0, step


. , .
, t>=t0, 1.
1 y, .

,
(m, n k ) .
,
OCTAVE.
: y .
, ustep.m.
. ,
, t=0,
ustep
, :
OCTAVE

. 44 99

. . .

t=-1:0.1:4;
v = ustep(t, 0) - ustep(t, 1);
plot (t, v)
axis ([-1 4 -1 2])

, 7.

7: , ,
ustep.

( OCTAVE ) :
who

*** dynamically linked functions:


dispatch
*** currently compiled functions:
_plt2_ _plt_ isscalar isvector rows
_plt2vv_ axis isstr plot ustep
*** local user variables:
tv
m n ustep
,
(workspace). , e.g. y
, e.g. y rectsin script,
y ustep.
.

OCTAVE

. 45 99

. . .

9.

(Matrices and vectors)

.
, mxn, m
n . , 2x3:

5 7 9
A=

1 3 2
OCTAVE
, :
A=[5 7 9
-1 3 -2]

A=
5 7 9
-1 3 -2
, (semicolons)
, :
B=[2 0; 0 -1; 1 0]

B=
2 0
0 -1
1 0
-- (colon):
C = [1:3; 8:-2:4]

C=
1 2 3
8 6 4
(
for loop):

D = [1 2 3];
D = [D; 4 5 6];
OCTAVE

. 46 99

. . .

D = [D; 7 8 9]

D=
1 2 3
4 5 6
7 8 9

9.1

(Matrix multiplication)

, * ,
( ):
A*B

ans =
19 -7
-4 -3
B*C

ans =
2 4 6
-8 -6 -4
1 2 3
A*C

error: operator *: nonconformant arguments (op1 is 2x3, op2 is 2x3)


error: evaluating binary operator * near line 11, column 2

. A*C,
15.
,
. , ,
. 1xn ,
mxn :
x = [1 0 3]

15

, , : (lxm)*(mxn) (lxn).
A*C, (2x3)*(2x3),
. ,
.
OCTAVE

. 47 99

. . .

x=
103
A*x

error: operator *: nonconformant arguments (op1 is 2x3, op2 is 1x3)


error: evaluating binary operator * near line 12, column 2

9.2

(The transpose operator)


. . ,
A AT. OCTAVE () :
A

A=
5 7 9
-1 3 -2
A

ans =
5 -1
7 3
9 -2
A*x

ans =
32
-7
x ,
.

9.3

(Matrix creation functions)

OCTAVE .
ones zeros,
1 0.

OCTAVE

. 48 99

. . .

(identity matrix).
.
I , OCTAVE
eye. ,
:
I = eye(4)

I=
1
0
0
0

0
1
0
0

0
0
1
0

0
0
0
1


:
I * [5; 8; 2; 0]

ans =
5
8
2
0
(identity matrix) ,
:
1
D = 0
0

0
7
0

0
0
2

, OCTAVE
diag :
diag([-1 7 2])

ans =
-1 0 0
0 7 0
0 0 2

OCTAVE

. 49 99

. . .

diag ,
, , .
:
diag(A)

ans =
5
3

, ,
.
,
.
:
E = []

E=
[]

9.4

(Building composite matrices)


,
:
comp = [eye(3) B;
A zeros(2,2)]

comp =
1 0
0 1
0 0
5 7
-1 3

0
0
1
9
-2

2
0
1
0
0

0
-1
0
0
0

- ,
. , OCTAVE
.

OCTAVE

. 50 99

. . .

9.5

(Matrices as tables)

,
:
t=0:0.2:1;
freq=[sin(t) sin(2*t), sin(3*t)]

freq =
0
0.1987
0.3894
0.5646
0.7174
0.8415

0
0.3894
0.7174
0.9320
0.9996
0.9093

0
0.5646
0.9320
0.9738
0.6755
0.1411

nth sin(t).
, .

.
.

9.6

(Extracting bits of matrices)

,
(). ,
( ,
y x). :
J = [1

2
5

3
6

4
7

11 13 18 10];
J(1,1)

ans =
1
J(2,3)

ans =
7
J(1:2, 4) %Rows 1-2, column 4

OCTAVE

. 51 99

. . .

ans =
4
8
J(3,:) %Row 3, all columns

ans =
11 13 18 10

: ,
.

:
J(3, 2:3) = [-1 0]
J=
1
5
11

2
6
-1

3
4
7
8
0 10

10. (Basic matrix functions)


OCTAVE .
,
.
+ . , OCTAVE
.* ./,
.
.^ .
OCTAVE ,
(. 6) .
6: (Basic matrix
functions and decompositions)

eye

Create an identity matrix

zeros

Create a matrix of zeros

ones

Create a matrix of ones

rand

Create a matrix filled with random numbers

diag

Create a diagonal matrix, or extract the diagonal of the given matrix

OCTAVE

. 52 99

. . .

inv

Inverse of a matrix

det

Determinant of a matrix

trace
eig

Trace of a matrix
Calculate the eigenvectors and eigenvalues of a matrix

rank

Calculate an estimate of the rank of a matrix

null

Calculate a basis for the null space of a matrix

rref

Perform Gaussian elimination on an augmented matrix

lu

Calculate the LU decomposition of a matrix

qr

Calculate the QR decomposition of a matrix

svd

Calculate the SVD of a matrix

pinv

Calculate the pseudoinverse of a matrix

size .
, .
size(J)

ans =
3 4

(identity matrix) (-1=-1=).
. OCTAVE
inv:
A = [3 0 4
0 1 -1
2 1 -3];

inv(A)

ans =
0.1429 -0.2857 0.2857
0.1429 1.2143 -0.2143
0.1429 0.2143 -0.2143
A*inv(A) %Check the answer

OCTAVE

. 53 99

. . .

ans =
1.0000
0
0

0.0000
1.0000
0.0000

-0.0000
0
1.0000

, ,
OCTAVE .
(determinant) . ,
. det
:
det(A)

ans =
-14

11. Ax = b (Solving Ax = b)

. :

a11 x1 + a12 x2 + L + a1n xn = b1


a21 x1 + a22 x2 + L + a2 n xn = b2
M = M
am1 x1 + am 2 x2 + L + amn xn = bm
aij bi , xi
.
- :

a11
a
21
M

am1

a12
a22
M
am 2

L a1n x1 b1
L a2 n x2 b2
=
O M M M

L amn xn bm

Ax = b

, , b , x
.
OCTAVE ,
.
OCTAVE

. 54 99

. . .

11.1 (Solution when A is invertible)


n n
.
. :

x+ y =3

2x 3 y = 5
OCTAVE
-
:
A=[1 1
2 -3];

b=[3 5];

inv(A)*b

ans =
2.8000
0.2000
A*ans % (Just to check)

ans =
3.0000
5.0000
x = 2.8, y = 0.2.

11.2 LU (Gaussian elimination and


LU factorization)

, OCTAVE
, .

OCTAVE

. 55 99

. . .

LU (
16
) .
x=b, OCTAVE
,
.

11.3 (Matrix division and


the slash operator)
, ax=b, x,
x=b/a. - Ax=b, ,
x=A-1b.

, OCTAVE \ (
, /),
. ,
:
A\b

ans =
2.8000

0.2000


A-1b.
(. ).
AX=B X=A-1B XA=B X=BA-1,
.
, OCTAVE / ()
. , , ,
\ .
7.

7: OCTAVE \ /.
,

(Summary of Octaves slash operators. These use Gaussian elimination if the
16

rref [A b],
lu OCTAVE LU (. help ).
OCTAVE

. 56 99

. . .

matrix is invertible, and finds the least squares solution otherwise).

OCTAVE

AX=B

A-1B

(left
division (backslash))

XA=B

BA-1

(right
division (forward slash))

11.4 (Singular matrices and rank)


(slash operator)
, ,
(undetermined). :

u+v+w= 2
2u + 3w = 5

3u + v + 4 w = 6
Ax=b. OCTAVE
(slash operator), :
A=[1 1 1
203
3 1 4];
b=[ 2 5 6];
x=A\b;

warning: matrix singular to machine precision, rcond = 1.15648e-17


warning: attempting to find minimum norm solution
warning: dgelsd rank difficient 3x3 matrix, rank = 2
x=
0.69048
-0.11905
1.09524
A*x

% b

ans =
1.6667
4.6667
6.3333
!
OCTAVE .
OCTAVE

. 57 99

. . .

. (
x.
, .,
det(A)

ans = 5.5511e-16
, .
, ;
. rank OCTAVE
:
rank(A)

ans =

2
.
,
3u+v+4w=7 . ,
. ,
, OCTAVE .
(slash operator)
OCTAVE , .
, 17.

11.5 (Ill-conditioning)

(Ill-conditioned) .
. :

1 1 1 2
1 1.01 1 = 2.01

OCTAVE :
M=[1 1; 1 1.01]; b=[2; 2.01]; x=M\b

17

, .
, (slash operator)
. .
OCTAVE

. 58 99

. . .

x=
1.00000
1.00000
:
M(1,2)=1.005; x=M\b

x=
-0.0100000
2.0000000
0.5% X(1) 101%,
X(2) 100%!
(condition number),
. ,
,
.

OCTAVE cond:
cond(M)

ans = 402.01
ax10k,
k .
OCTAVE 15 ,
(15 k). ,
4x102, 2 , .
18.
, , cond
5.2432x1016. , .

11.6 : (Over-determined
systems: Least squares)
()
.
18

b
15 . ,
k .

OCTAVE

. 59 99

. . .

,
, . , m,
, n.
,
.
.
Ax=b,
:

x = (ATA)-1ATb

OCTAVE \ .
,
.
OCTAVE
pinv, .

11.7 : (Example: Triangulation)


,
.
.
:

2x y = 2
x+ y =5
6 x y = 5
OCTAVE
:
A = [2 -1; 1 1; 6 -1];
b = [2 5 -5];

x = inv(A*A)*A*b

x=
-0.094595
OCTAVE

. 60 99

. . .

2.445946
x=pinv(A)*b

x=
-0.094595
2.445946
x = A\b

x=
-0.094595
2.445946
, , .
8 .
,
,
:
x = linspace(-4, 4, 1000);
y1 = 2*x+2; y2 = -x +5; y3 = 6*x + 5;
A = [2 -1; 1 1; 6 -1]; b = [2 5 -5]; simeio = A\b;
plot(x, y1, x, y2, x, y3, simeio(1), simeio(2), *);
xlabel('x'); ylabel('y');
title (Plot of 2x-y=2, x+y=5, 6x-y=-5 and simeio=[-0.0946 2.446]);
legend(y1 = 2*x+2',' y2 = -x +5', y3 = 6*x + 5, simeio);
grid on;

OCTAVE

. 61 99

. . .

8: .

12. (More graphs)


OCTAVE
2D , GNUPlot.
, 3D , .
help GNUPlot
.

12.1 (Putting several graphs in


one window)
,
. subplot
. :

subplot(rows, columns, select)


select .
, .
, ,
9.
x = linspace(-10, 10);
subplot(2,1,1) % Specify two rows, one column, and select
% the top one as the current graph
plot(x, sin(x));
subplot(2,1,2);
plot(x, sin(x)./x);

OCTAVE

. 62 99

. . .

9: subplot, sine sinc .


subplot.

12.2 (3D plots)


OCTAVE 3D .
3D plot3, 3D plot.
, x, y z .
,
19.
t = 0:pi/50:10*pi;
x = sin(t); y = cos(t); z = t;
plot3(x, y, z);

10. xlabel ylabel


zlabel .
3D 3.

19


, .
: . x, y ( 3D z)

: ,
.

OCTAVE

. 63 99

. . .

10: plot3, .

12.3 (Changing the viewpoint)


3D ,
. (
.
).
820.
8: 3D (Mouse and Key
binds for interaction with 3D graphs). (LMB - Left Mouse Button, MMB Middle
Mouse Button), . 4.
(Mouse)
LMB + motion
<Ctrl> + LMB + motion
MMB + motion

Rotate View
Rotate axes (View update when button released)
Scale View

<Ctrl> + MMB + motion

Scale axes (View update when button released)

<Shift> + MMB + motion

vertical motion change ticslevel

Rotate right (<shift> increases amount)

Rotate up (<shift> increases amount)

Rotate left (< shift> increases amount)

Rotate down (<shift> increases amount)

OCTAVE view
, ( help view ).

20

MATLAB GUI.

OCTAVE

. 64 99

. . .

12.4 (Plotting surfaces)


3D ,
f(x, y), OCTAVE
.
,
. (grid)
meshgrid OCTAVE:
x = 2:0.2:4; % Define the x- and y- coordinates
y = 1:0.2:3; % of the grid lines
[X, Y] = meshgrid(x, y); %Make the grid

X Y x y .
. ,

f(x, y) = (x 3)2 (y 2)2

, :
Z=(X-3).^2 - (Y-2).^2;
surf(X, Y, Z)

surf . 11
, ,
surf, 3D .
Surf
1
0.5
0
-0.5
-13

2.5

1.5

12

2.5

3.5

11: - (saddle-shaped)
OCTAVE .
( 3 subplot(2, 2, i)).

OCTAVE

. 65 99

. . .

12.5 (Images and Movies)


,
(pixel). OCTAVE
.
cued.mat,
:
load cued
colormap(gray(64)) % Tell Octave to expect a grayscale image
image(a)

image . colormap OCTAVE


grey, 21.
OCTAVE (movies),
MATLAB .
.

13. (Eigenvectors and the


Singular Value Decomposition)
Ax=b, Ax=x,
(eigenvectors) (eigenvalues) .
, OCTAVE
.

13.1 eig (The eig function)


eig OCTAVE .
, , :
A = [1 3 -2
351
-2 1 4];
eig(A)

ans =
-1.5120
4.9045
6.6076

21

colormap(jet) (
colormap). colormap
3D .

OCTAVE

. 66 99

. . .

, :
[V, D] = eig(A)

V=

-0.818394 -0.315302 -0.480434


0.434733 0.207055 -0.876433
-0.375818 0.926128 0.032380
D=

-1.51204 0.00000 0.00000


0.00000 4.90448 0.00000
0.00000 0.00000 6.60756
V ,
.
. , U
, A = UU1.

eig:
V*D*inv(V)

ans =

1.0000 3.0000 -2.0000


3.0000 5.0000 1.0000
-2.0000 1.0000 4.0000
A.

13.2 (The Singular Value Decomposition)


,
UU1 .
(Singular Value Decomposition (SVD)) ,
.
, .
SVD mn A A = Q1Q2T , :
Q1 mm AAT
Q2 nn ATA
mn AAT
ATA ( , )

OCTAVE

. 67 99

. . .

:
T

Q2 ( nxn )
644
4
7444
8
Q1 ( mxm )
A( mxn )
( mxn )

644
4
7444
8 64748
644
4
7444
8

m =
m
m
n

n m n

,
, , i:

, Q1
Q222.
Q1 Q2T .
, ,
A .
, .
. ,
, (rank deficient).
, , .
SVD ,
. ,
( Ax = 0) Q2
. SVD
(ill-conditioned) SVD
.

22

Q2T, , Q2.
OCTAVE

. 68 99

. . .

13.3 : (Approximating matrices: Changing


rank)
SVD
, .
, 1,
. Q1 Q2
.
, A Q1Q2T,
( ) Q1 Q2,
, .
,
A, .

13.4 svd (The svd function)


SVD OCTAVE svd.
eig, (singular values),

:
A = [1 3 -2 3
3515
-2 1 4 2];

svd (A)

ans =

8.9310
5.0412
1.6801
[U, S, V] = svd (A, 0)

U=

-4.6734e-01 3.8640e-01 7.9516e-01


-8.6205e-01 3.3920e-04 -5.0682e-01
-1.9611e-01 -9.2233e-01 3.3294e-01
S=

8.93102 0.00000 0.00000


0.00000 5.04125 0.00000
OCTAVE

. 69 99

. . .

0.00000 0.00000 1.68010


V=

-0.297983
-0.661559
-0.079700
-0.683516

0.442764 -0.828029
0.047326 0.109729
-0.885056 -0.455551
-0.135631 0.307898

U*S*V % Check Answers

ans =

1.00000 3.00000 -2.00000 3.00000


3.00000 5.00000 1.00000 5.00000
-2.00000 1.00000 4.00000 2.00000
OCTAVE .

13.5 svd (Economy SVD)


mn m > n, ,
:
[U, S, V] = svd (A)

U=

-0.22985 0.88346 0.40825


-0.52474 0.24078 -0.81650
-0.81964 -0.40190 0.40825
S=

9.52552 0.00000
0.00000 0.51430
0.00000 0.00000
V=

-0.61963 -0.78489
-0.78489 0.61963
A = U*S*V,
U : S,
. ,
S. :

OCTAVE

. 70 99

. . .

A ( mxn )
64748

m =

Q2 ( nxn )
( nxn )
Q1 ( mxm )
6474
8 6474
8
64748
M
M
M

m
n
n

m n n

OCTAVE SVD , 0
(, ):
[U, S, V] = svd (A, 0)

U=

-0.22985 0.88346
-0.52474 0.24078
-0.81964 -0.40190
S=

9.52552 0.00000
0.00000 0.51430
V=

-0.61963 -0.78489
-0.78489 0.61963
,
.

14. (Complex numbers)


, OCTAVE
, .
OCTAVE , :
z1 = 4-3i

z1 = 4 - 3i

, i j OCTAVE
) :

1 (

z2 = 1 + 3*j
OCTAVE

. 71 99

. . .

z2 = 1 + 3i
,
:
z2-z1

ans = -3 + 6i
z1+z2

ans = 5
z2/z1

ans = -0.20000 + 0.60000i


z1^2

ans = 7 - 24i
OCTAVE ,
, , . (. 9).
9: (Complex number functions)
(function)

(meaning)

(definition ( z = a + bi ))

imag

Imaginary part

real

Real part

abs

Absolute value (modulus)

conj

Complex conjugate

angle

Phase angle (argument)

r= z
z = a bi

= tan 1 (b / a )

, sin(x) ex,
:
sin (z2)

OCTAVE

. 72 99

. . .

ans = 8.4716 + 5.4127i


exp (j*pi) %Should be -1

ans = -1.0000e+00 + 1.2246e-16i


exp (j*2)

ans = -0.41615 + 0.90930i


cos (2) + j*sin(2) %Should be the same as e^2i

ans = -0.41615 + 0.90930i


, , .

14.1 (Plotting complex numbers)


plot OCTAVE .
Argand ( x-
y- ):
plot (z1,*, z2,*)
axis ([-5 5 -5 5])

12.

12: z1 = 4 3i z2 = 1 + 3i
plot.

OCTAVE

. 73 99

. . .

14.2 (Finding roots of polynomials)


, OCTAVE roots.
OCTAVE, .
, :

x5 + 2 x 4 5 x 3 + x + 3 = 0
:
c = [1 2 -5 0 1 3];

roots :
roots (c)

ans =

-3.44726 + 0.00000i
1.17303 + 0.39021i
1.17303 - 0.39021i
-0.44940 + 0.60621i
-0.44940 - 0.60621i

15. (Polynomial manipulation)


Octave (
). , c N+1
N:
p(x) = c(1) x^N + ... + c(N) x + c(N+1)

c
x , :
c = [1 2 3]; N = length(c)-1; val = dot( 2.^(N:-1:0), c );

val = 11
,
.
, Horner,
polyval (c, x) Octave.
p(x) (. 13) [-1, 1]
:

OCTAVE

. 74 99

. . .

x=linspace(-1, 1);
plot(x, polyval(c, x))

13: p(x).

x , c
-. x
Octave,
.
polyvalm (c, x) , . polyvalm (c, x)
,
polyval.
x .

15.1 (Finding Roots)


Octave
(companion) (. compan,
), (eigenvalues).

roots (v) v N ,
:

v(1) * z^(N-1) + ... + v(N-1) * z + v(N)

, p(x) =
x^2 5:
c = [1, 0, -5];
roots(c)
OCTAVE

. 75 99

. . .

ans =

-2.2361
2.2361
+/- sqrt(5) +/- 2.2361.
compan.

15.2 compan (c)


compan (c) (companion)
c. (companion) :

c2 / c1
1

A= 0

M
0

c3 / c1 L c N / c1
0
L
0
1
M

L
O

0
M

c N +1 / c1

15.3
conv (a, b).
, p(x)=x+2 q(x)=x^2+4x+8:
p=[1, 2];
q=[1, 4, 8];
z=conv(p, q)

z=

16

16

, , z(x) = p(x) q(x) = x^3 + 6x^2 + 16x + 16.


deconv(a,b). ,
z(x) q(x) :
[p, r] = deconv(z, q)

p=1 2
r=0 0

OCTAVE

0 ( .)

. 76 99

. . .

15.4
polyder (p).
, p(x) = 3x^3 4x^2 x + 2 :
p=[3, -4, -1, 2];
polyder(p)

ans = 9

-8

-1

15.5
poly . :
A=[1, 2, 3; 0, 2, 4; 0 0 5]

A=

123
024
005
p=poly(A)

p=

-8

17

-10

(. ) :
roots(p)

ans =

5.0000
2.0000
1.0000
eig:
eig(A)

ans =

1
2
5
OCTAVE

. 77 99

. . .

15.6 (curve fitting)


(curve fitting),
(regression). ,
,
, , .
.
),
(interpolant),
.
,
, ,
(least squares method).

Octave polyfit, :
(xi, yi), i= 1,...,N+1 x
y, . , :
p = polyfit(x, y, )

p
.
=,
(xi, yi), <N
. >N,
. .
, :
x = [1 2 3 4]; y = [2 6 4 8];

,
p = polyfit(x, y, 3)

p = 2 -15

35

-20

p (x) = 2x^3 15x^2 + 35x 20


, 4 3.

OCTAVE

. 78 99

. . .

p(t) (. 14), t [1,


4] , :
t = linspace(1, 4);
p_times = polyval(p, t);
plot(t, p_times, x, y, 'o')
xlabel('x')
ylabel('y')
legend('p(x)','data')

14: p(x).

16. OCTAVE -

,
( )
.

.

OCTAVE

. 79 99

. . .

d2
d
y (t ) + b y (t ) + ky (t ) = u (t )
2
dt
dt

:
k.........
M .......
y(t) ....
,
u(t) ...

b ........
.
M=10, =5 b=2,
10 p 2 + 2 p + 5 = 0 .
OCTAVE
:
p = [10 2 5]; roots (p)

ans =

-0.10000 + 0.70000i
-0.10000 - 0.70000i

.
x1 (t ) = y (t )
x&1 (t ) = y& (t ) = x2 (t ) ,

:

0
x&1 (t )
x& (t ) =
k
=
x& 2 (t )
M

OCTAVE

1
0
x1 (t )

b
+ 1
x2 (t )
M
M
x
(
t
)

y (t ) = [1 0 ] 1
x 2 (t )

u (t ) = Ax (t ) + bu (t )

. 80 99

. . .

M=10, =5 b=2 :

1 x1 (t ) 0
x&1 (t ) 0
x& (t ) = 0.5 0.2 x (t ) + 0.1 u (t )
2
2
x (t )
y (t ) = [1 0] 1 = Cx(t ) + 0u (t )
x2 (t )

OCTAVE
ss (state space) :
A = [0 1; -0.5 -0.2];
b = [0; 0.1];
c = [1 0];
sys = ss(A, b, c, 0);

16.1
y (t ) 0.
,
y (0) = 1 dy (0) / dt = y& (0) = 2 ,

OCTAVE lsim :
t = [0:0.1:100];
u = zeros(1001, 1);
y0 = 1; 2];
y = lsim (sys, u, t, y0);
mx=max(abs(y)) %
plot(t,y,'Color',[0 0 1], 'LineWidth',2, mx, *);
title('Free response of a Mass Spring System');
xlabel('t'), ylabel('y(t)'), grid('on');

mx = 2.6723
15
mx = 2.6723 .

OCTAVE

. 81 99

. . .

15: -.

16.2
Dirac (t)
:
impulse(sys, 1, 100, 1000);
title('Impulse response of a Mass Spring System');

1 , 100
(. 16), 1000
.

16: (Impulse) .

OCTAVE

. 82 99

. . .

16.3
step
:
step(sys, 1, 100, 1000);
title('Step response of a Mass Spring System');

1 , 100
(. 17), 1000
.

17: (Step) .

16.4
(. 17)

40 sec. (feedback)

. .
(linear regulator).
:

x& (t ) = Ax(t ) + Bu (t )

OCTAVE

. 83 99

. . .

J = x (t )Qx(t ) + u T (t ) Ru (t ) dt
to

Q 0 R > 0 .
OCTAVE lqr
u (t ) = Kx (t )

x& (t ) = [ A BK ] x(t ) = Acl x(t ) ( Acl ).


lqr, , Riccati
Acl . lqr :
[k, p, e] = lqr (a, b, q, r)

15 0
0
0 25

Q =

R = 0.25 > 0 OCTAVE


18:
A = [0 1; -0.5 -0.2];
b = [0; 0.1];
c = [1 0];
q = [10 0; 0 25];
r = 0.25;
[k, p, e] = lqr (A, b, q, r);
Acl = A b*k;
sys = ss(Acl, b, c, 0);
step(sys, 1, 100, 1000);
title('Step response of the Closed loop Mass Spring System');

OCTAVE

. 84 99

. . .

18: .

17 18
( )
.

17. OCTAVE
(Digital signal processing (DSP))

. ,
sonar radar, , ,
, , ,
, , , .

17.1 (Convolution and Filtering)


(convolution). OCTAVE
conv - :
,
conv([1 1 1],[1 1 1])

ans =
1

OCTAVE

. 85 99

. . .

y(k) x(k)
(impulse response) h(k). ,
:

y ( k ) = h( k ) * x ( k ) =

h ( k n) x ( n)

n =

h(k) x(k)
,
conv. x(k) x, h(k)
h, :
x = randn(5,1);
h = *[1 1 1 1];

% 5 ( 5x1)
% 4

y = conv(h,x);

y=

0.43699
0.29990
0.16408
0.32081
-0.66092
-0.52393
-0.38800
0.54474

17.2 (Filters and Transfer Functions)


, - Y(z) y(n)
- X(z) x(n) :

Y (z) = H ( z) X (z) =

b(1) + b(2) z 1 + ... + b(n + 1) z n


X ( z)
a(1) + a(2) z 1 + ... + a(m + 1) z m

H(z) . b(i) a(i)


n m.
OCTAVE ,
(b) (a).

OCTAVE

. 86 99

. . .

a b
:
n = 0 ( b ), Infinite Impulse
Response (IIR) , all-pole, recursive, autoregressive (AR) .
m = 0 ( a ), Finite Impulse
Response (FIR), all-zero, nonrecursive, moving-average (MA) .
n m , IIR, pole-zero, recursive,
autoregressive moving-average (ARMA) .
AR, MA, ARMA
.

17.3 filter (Function filter)


z-
. a(1) = 1,
z- (inverse z-transform) :

y (k ) + a2 y (k 1) + ... + am +1 y (k m) = b1 x(k ) + b2 x(k 1) + ... + bn +1 x(k n)


y(k) :

y (k ) = b1 x(k ) + b2 x(k 1) + ... + bn +1 x(k n) a2 y (k 1) + ... + am +1 y (k m)

(standard) ,
y(1) .
:

y (1) = b1 x(1)
y (2) = b1 x(2) + b2 x(1) a2 y (1)
y (3) = b1 x(3) + b2 x(2) + b3 x(1) a2 y (2) a3 y (1)
M = M

filter OCTAVE.
, (lowpass) :

OCTAVE

. 87 99

. . .

b = 1;

a = [1 -0.9]; %

b a
. x
:
y = filter(b, a, x);
filter , .
y x. a
1, filter a(1) .

17.4 (Impulse Response)



:

1, n = 1
x ( n) =
0, n 1

OCTAVE .
:
imp = [1; zeros(49, 1)];

b = 1 a = [1 -0.9] :
h = filter(b, a, imp);

17.5 Fourier (Discrete Fourier Transform)


Fourier (discrete Fourier transform), DFT,
. DFT
Fourier (fast Fourier transform
(FFT)).
OCTAVE fft ifft
Fourier (discrete Fourier transform, DFT) .
x DFT X (
), :

OCTAVE

. 88 99

. . .

N 1

X (k + 1) = x(n + 1)WNkn
n=0

x(n + 1) =

WN = e

j(

2
)
N

1
N

N 1

X (k + 1)W

kn
N

k =0

,
:
t = (0:1/100:10-1/100);

x = sin(2*pi*15*t) + sin(2*pi*40*t);

DFT , :
y = fft(x);

% DFT x

m = abs(y); p = unwrap(angle(y)); %

(. 19) :
f = (0:length(y)-1)*99/length(y); % Frequency vector
plot(f, m); title('Magnitude');
set(gca,'XTick',[15 40 60 85]);
figure; plot(f, p*180/pi); title('Phase');
set(gca, 'XTick',[15 40 60 85]);

19: y=fft((sin(2*pi*15*t) + sin(2*pi*40*t)).

OCTAVE

. 89 99

. . .

Fourier (
ifft) x
( ).
t = (0:1/255:1);
x = sin(2*pi*120*t);
y = real(ifft(fft(x)));

18.

18.1 image
image.
:
http://octave.sourceforge.net/packages.php.

80. details
download .
Synaptics package manager.

(grayscale) (). grayscale
[
].
:
. # .

: http://octave.sourceforge.net/image/overview.html

18.2
clc # clear screen -
# imread()
# .
myimage1 = imread("/home/antony/Octave_scripts/d5.gif"); # get
# original image no.1
myimage2 =imread("/home/antony/Octave_scripts/appLBW.jpg"); # get
OCTAVE

. 90 99

. . .

# original gray image no.1


myimage3 =imread("/home/antony/Octave_scripts/apple.jpg"); # get
# original image no.3
# imshow(_)
# .
imshow(myimage1)

# .1

. 1

18.3
# isgray(1) 1 1
# . , (), 0.
# isgray() # Boolean. Returns true for a gray-scale intensity image.
# flipud(myimage1)
# try with a colour image to see the difference
#
if (isgray(myimage1))
cc=flipud(myimage1);
# flip a 2-D (B/W) image;
disp('Image is grayscaLe')
imshow(cc)
# show result
else
disp('Image is NOT grayscaLe')
end # end_if
rgb2gray .
# rgb2gray # Converts an RGB image to a gray scale image
OCTAVE

. 91 99

. . .

myimage2 = imread("/home/antony/Octave_scripts/d5.gif"); # get


# original image no.2
d6= rgb2gray(myimage2); # convert to gray
BOOL1 = isgray(d6)
# check if gray [should be "1"]
imshow(d6)
# show result
# j=histeq(d6)
# . d6

.2

#
#
#
#

ALTERNATIVELY, --- :
d7= rgb2gray(imread("/home/antony/Octave_scripts/d5.gif"));
get original image no.1
imshow(d7)

# ,
# :
d7=flipud(d6);
imshow(d7)

# flip a 2-D (B/W) image;


# show result

.3 [7]

OCTAVE

. 92 99

. . .

18.4

# imrotate :
## imrotate(IMGPRE, THETA, METHOD, BBOX, EXTRAPVAL)
d8= imrotate(d6, 30, "nearest", "loose", 0); # 30
imshow(d8)
# show result

.4 30 [8]

d9= imrotate(d6, -30, "nearest", "crop", 0); #


# -30 ,
# kopse o,ti perisseuei apo to arxiko plaisio
imshow(d9)

# show result

.5 -30 [9]

d10 =imresize(d6,0.5);
OCTAVE

# 50%
. 93 99

. . .

imshow(d10)

# show result

.6 50% [10]

18.5
# 2- 3-
[n_row,n_col] =size(myimage1) # Return the number rows and columns
# of myimage1
zmax=max(max(myimage1)) # find max value
zmin=min(min(myimage1)) # find min value
imshow(myimage1) # show image before
aa=myimage1; # define a new img_variable "aa"
for i=1:n_row
for j=1:n_col
if (myimage1(i,j) < zmax*0.8) # transformation
# [0,8]
#
aa(i,j)=1; #
# , 1
end # end_if
end # end_for_coL
end # end_for_row
imshow(aa) # show image after filtering

OCTAVE

. 94 99

. . .

.7

.7

().
.

19.

19.1 y = f(x) -
:
x=0:0.1:1; y=sin(pi*x); % help elfun
, for-end ( )
x=0:0.1:1; n=length(x);
for i=1:n;
y(i)=sin(pi*x(i));
end;
(Vectors are matrices):
y=x*x;
% ; ;
x2=0:0.2:1; y=x+x2;
% ; ;
y=x*x %
y;
y=x*x
% y;
(Componentwise operation):
y=x.*x
%
y=x.^3
% carat
y=2*x
%
y=1./x
%
(Accessing subvectors):
x=0:0.1:1;
n=length(x)
x2=x(5:10)
% x2;
x2=x([1,3,4,11]) % x2;
x2=x(2:4:11)
% x2;
OCTAVE

. 95 99

. . .

Accessing submatrices:
a=[100 90 85; 117 110 108; 84 84 84; 96 90 88];
[m, n]=size(x)
a2=a(2,3)
% a2;
a2=a(:,2)
% a2;
a2=a(2,:)
% a2;
a2=a(2:3,:)
% a2;
a2=a(2:3,[1,3]) % a2;
sum (The sum command (type help sum)):
y = [1, 4, 2, 10]; sum(y);
% y
sum(y(1:2:4));
% ;
sum(a(:,1));
% a . ;

19.2 (plots)
plot (Plot command):
x=0:.1:1; y =sin(2*pi*x);
plot(x, y); %
Exercise:
x=[0,1]; y=sin(2*pi*x);
plot(x,y);
% ;
(Options):
Line type options: -,:,--,-.
plot(x,
plot(x,
plot(x,
plot(x,

y,-);
y,:);
y,--);
y,-.);

(Color options): y, m, c, r, g, b, w, k
plot(x, y, g);
plot(x, y, r)

% green line (line is default)

(Marker options): ., o, x, +, *, s, d, v, ^, <, >, p, h (type help plot)


plot(x, y, x);

% blue star (blue is default)

(Using several options together):


plot(x, y,*-r);

% red line with star markers

(Plotting several curves):


OCTAVE

. 96 99

. . .

x=0:0.05:1; y1=sin(2*pi*x); y2=cos(2*pi*x);


plot(x, y1, x, y2)
plot(x, y1, -b, x, y2, --r)
x=0:0.05:2; y1=x; y2=x.^2; y3=x.^3; y4=x.^4;
plot(x, y1, -b, x, y2, --r, x, y3, *g, x, y4, -c)
, hold (Alternative, using hold command):
x=0:0.05:1; y1=sin(2*pi*x); y2=cos(2*pi*x);
plot(x, y1,-b)
hold on
plot(x, y2,--r)
hold off
(The axis command):
axis([0,2,0,4])
axis equal
axis square % help axis
(Labelling):
xlabel(time t)
ylabel(position s(t))
ylabel(position s(t),FontSize,16)
title(Its important to label your graphs!)
text(0.6, 2,some text,FontSize,16)
set(gca,FontSize,16)
legend(x,x^2)
(Simplest Plots):
plot(x)
% Plots x vs its index, quick way to see what is in x
plot(x1, x2)
% Careful! This does not plot x1 vs index
% and x2 vs index. Instead, plots x2 vx x1
plot(x1,x2,x3)
% and this gives you an error. Why?

19.3 (Miscellaneous commands)


(Comments):
% This is a comment
The help and lookfor commands:
help zeros
help for
help
lookfor factorial

% you need to know exact command name


% lists topics for which there is help
% if you do not know the exact command name

The print command:


print
OCTAVE

% prints current figure to current printer


. 97 99

. . .

print -deps
print -depsc
print -dps

% prints current figure to .eps file


% prints current figure to color .eps file
% prints current figure to .ps file

The figure command:


figure
figure(2)

% opens new figure


% makes figure 2 the current figure

The pause command:


pause
pause(2)

% What does this do?


% What does this do?

The continuation symbol:


x=[0 1 2 3 4 5 ...
6 7 8 9 10]

% To continue the current command


% to the next line, use ...

The clear command:


clear
clear x y ...

% clears all variables from memory


% clears listed variables from memory

The clf command:


clf

OCTAVE

% clears current figure

. 98 99

. . .

(References)

[1]

www.octave.org http://www.gnu.org/software/octave/

[2]

P.J.G. Long, Introduction to Octave, Department of Engineering, University of Cambridge,


September 2005, http://smilodon.berkeley.edu/octavetut.pdf

[3]

Hubert Selhofer, revised by Marcel Oliver, Introduction to GNU Octave, 2003/09/10,


http://math.jacobs-university.de/oliver/teaching/iub/resources/octave/octave-intro.pdf

[4]

Kai Arras, Octave/Matlab Tutorial, http://srl.informatik.uni-freiburg.de/downloadsdir/OctaveMatlab-Tutorial.pdf

[5]

John W. Eaton, David Bateman, Sren Hauberg, GNU Octave, A high-level interactive
language for numerical computations, Edition 3 for Octave version 3.2.2, July 2007.

[6]

MATLAB (http://www.mathworks.com/)

[7]

, , ,
http://anadrasis.math.auth.gr/S.Vologiannidis.htm

[8]

. - . , MATLAB, ISBN 978-9963-644-57-5,


Kantzilaris, Nicosia, Cyprus 2007, http://www.ucy.ac.cy/~georgios
http://www.ucy.ac.cy/~xenophontos.

OCTAVE

. 99 99

You might also like