22
Octave: Overview for Statistical Computing Kerby Shedden Department of Statistics University of Michigan Last update: 9/2004 1. Using Octave as a calculator 2. Comments, broken lines, simple output control 3. Variables 4. Arithmetic 5. Basic array manipulations 6. Some useful built-in vector and array functions 7. Array slices 8. Conditional execution 9. Looping 10. Boolean operators and functions 11. Operations on sets 12. Sorting 13. Defining new functions 14. Compatibility with Matlab 1

Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

Octave: Overview for Statistical Computing

Kerby SheddenDepartment of StatisticsUniversity of MichiganLast update: 9/2004

1. Using Octave as a calculator

2. Comments, broken lines, simple output control

3. Variables

4. Arithmetic

5. Basic array manipulations

6. Some useful built-in vector and array functions

7. Array slices

8. Conditional execution

9. Looping

10. Boolean operators and functions

11. Operations on sets

12. Sorting

13. Defining new functions

14. Compatibility with Matlab

1

Page 2: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

1. Using Octave as a calculatorYou can enter simple arithmetic expressions directly into Octave, and the result is printedback to the screen.

octave:1> 4+2

ans = 6

octave:2> 9/4

ans = 2.2500

octave:3> 2^3

ans = 8

octave:4> sin(pi/2)

ans = 1

octave:5> log(37)

ans = 3.6109

octave:6> rem(11,3)

ans = 2

octave:7> 2*(5-1)

ans = 8

octave:8> 2*5-1

ans = 9

Most of the time, you will not want to type programs directly into the Octave prompt.Instead, you should prepare your programs in a file (using your favorite text editor such asNotepad or the DOS editor), and then run the program from within Octave.

For example, save these commands into a file called “prog.m”:

disp(2*(5-1));

disp(3^2);

3^2

Next type source(’prog.m’) or just prog at the Octave prompt:

octave:1> source(’prog.m’)

8

9

ans = 9

Note that if you end a statement with a semicolon (;) Octave will not print the result (thisis useful in a longer program where you don’t want the result of every line printed to thescreen). Also, you may enclose a statement in disp() to print the result without havingOctave print “ans = “ (this makes the output clearer).

2

Page 3: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

2. Comments, broken lines, output controlAny line of Octave code that begins with # or % will be ignored (for Matlab only % behavesthis way). This is used for placing comments into script files. If a line of code is too longto fit into one line on the screen, enter an ellipsis (...) and continue on the next line.Most Octave statements return a value (often as a side effect of the primary action of thestatement). This return value will be printed to the terminal unless the line is terminatedwith a semicolon (;).

## This is a comment in Octave.

%% This is a comment in both Matlab and Octave.

%% This is a long statement that is broken over two lines.

%% It is better to indent the continued lines a bit.

disp(1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + ...

11 + 12 + 13 + 14 + 15);

%% A ’5’ will be printed to the screen.

3+2

%% This statement does nothing.

3+2;

3. VariablesVariables in Octave can be either scalars or arrays. A scalar variable holds a single numericalvalue, while an array variable holds a table of values. Variables can be initialized with aspecific numerical value (a literal), or with the result of an expression:

%% The scalar variable x is being initialized with the value 7.

x = 7;

Critical point: A statement using a single = symbol, such as x = 7, is an assignment state-ment. That is, it sets the value of x to 7. If x previously had some other value, that value islost. Note that this is different from the usual mathematical meaning of =, where a statementlike x = 7 is interpreted as a question – “is x equal to 7?”. The answer to this question maybe yes or no, but in either case, the value of x is not changed by asking the question, it isstill 7. In Octave, = is an assignment – it changes the value of a variable. If you want toask a question, use == (double equals).

%% The scalar variable y is being initialized with the result of

%% the expression 1 + 7/2.

y = 1 + x/2;

%% The array variable w is being initialized with a literal 1x5

3

Page 4: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

%% array.

w = [1, 2, 3, 4, 5];

%% The array variable z is being initialized with a literal 5x1

%% array.

z = [1; 2; 3; 4; 5];

%% The array variable a is being initialized with a literal 3x3

%% array.

a = [1, 2, 3; 3, 4, 5; 4, 3, 2]

Written in common mathematical notation, the values of z and a are:

w =(

1 2 3 4 5)

z =

12345

a =

1 2 33 4 54 3 2

Array literals are enclosed in brackets ([]), with the values given in row major order, meaningthat the values in the first row are listed first, followed by the values in the second row, andso on (as in reading a page of text). The values within a row are separated by commas (,),and the rows are separated from each other by semicolons (;).

The shape of an array refers to the number of rows and the number of columns in the array.You can determine the shape of a array in Octave using the size() function.

%% Following this line, u will have the value [1, 5].

u = size(w);

%% Following this line, v will have the value [5, 1].

v = size(z);

%% Following this line, w will have the value [3, 3].

w = size(a);

If the number of rows in an array is one (a 1×n array), the array can be called a row vector.If the number of columns in an array is one (a n×1 array), the array can be called a columnvector. In general, any array that has either one row or one column is a vector. An arraythat has both one row and one column (a 1× 1 array) is a scalar. An array with zero rowsor columns (or both) is empty.

You can use either size or length to determine the number of elements in a vector:

%% A row vector with 6 elements.

v = [2,3,1,8,9,2];

4

Page 5: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

%% Prints ’1 6’.

disp(size(v));

%% Prints ’6’.

disp(length(v));

%% A column vector with 4 elements.

v = [2;1;2;9];

%% Prints ’4 1’.

disp(size(v));

%% Prints ’4’.

disp(length(v));

There are easy ways to generate certain types of arrays that arise frequently.

%% Produces [2, 3, 4, 5, 6] (this is called a ’range’).

z = [2:6];

%% Produces [1, 5, 9, 13, 17] (a range with a ’stride’ of 4).

z = [1:4:20];

%% Produces [0, 0; 0, 0; 0, 0].

z = zeros(3,2);

%% Produces [1, 1, 1; 1, 1, 1].

z = ones(2,3);

%% Produces [1, 0, 0; 0, 1, 0; 0, 0, 1].

z = eye(3);

4. ArithmeticThe basic arithmetic operations +, -, *, /, and ^ act as expected:

%% Assigns 5 to x.

x = 2 + 3;

%% Assigns -1 to x.

x = 2 - 3;

5

Page 6: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

%% Assigns 6 to x.

x = 2 * 3;

%% Assigns 2.5 to x.

x = 9 / 4;

%% Assigns 8 to x.

x = 2 ^ 3;

There are three forms of rounding: ceil rounds toward +∞, floor rounds toward −∞, andround rounds to the nearest integer.

%% Assigns 8 to x.

x = ceil(7.8);

%% Assigns 7 to x.

x = floor(7.8);

%% Assigns -3 to x.

x = ceil(-3.4);

%% Assigns -4 to x.

x = floor(-3.4);

%% Assigns -3 to x.

x = round(-3.4);

%% Assigns 8 to x.

x = round(7.8);

Integer division of a by b can be carried out with the rem (remainder) function. A funda-mental fact of arithmetic is that for a given a and b there is a unique way to write a = db+ rwhere d and r are integers and 0 ≤ r < b. The function rem(a, b) returns r, and the valueof d can be obtained using floor(a/b).

5. Basic array manipulationsThe value of a single element in an array can be accessed by subscripting the array usingparentheses. If M refers to the entire array, then M(3,2) refers specifically to the number inrow 3 and column 2. Note that the row index always comes before the column index, andboth indices begin by counting the with ’1’ (so M(1,1) is the value in the upper left cornerof M). If the array is a vector, values can be accessed using a single index.

%% Construct a column vector with 5 values.

v = [3; 1; 2; 7; 9];

6

Page 7: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

In usual mathematical notation:

v =

31279

.

%% This displays a ’7’.

disp(v(4));

Sometimes it is useful to reference the last element of a vector:

%% This displays a ’9’.

disp(v(length(v)));

%% Construct a 2x3 array.

z = [1, 3, 2; 4, 8, -1];

In usual mathematical notation:

z =

(1 3 24 8 −1

).

%% This displays a ’2’.

disp(z(1,3));

%% After this line, z will have value [1, 3, 2; 4, 0, -1].

z(2,2) = 0;

In usual mathematical notation, the new value of z is

z =

(1 3 24 0 −1

).

The transpose A′ of an array A is defined by A′(i, j) = A(j, i). If A is p× q, then A′ is q× p.Here is an example:

A =

(3 1 20 9 5

)A′ =

3 01 92 5

In Octave, the transpose can be obtained using the quote (’) operator.

A = [2,3;4,5];

%% After this line, B has the value [2, 4; 3, 5].

B = A’;

7

Page 8: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

Two arrays are conformant if they have the same shape. In Octave, conformant arrays canbe added, subtracted, multiplied, and divided element-wise using the four operators: + -

.* ./. Note that the point (.) before the element-wise multiplication (.*) and division(./) operators is essential. Without the point, linear-algebraic multiplication and divisionare performed. The following examples demonstrate these four operators.(

2 3−1 0

)+

(8 04 2

)=

(10 33 2

)(

2 3−1 0

)−

(8 04 2

)=

(−6 3−5 −2

)(

2 3−1 0

).∗

(8 04 2

)=

(16 0−4 0

)(

2 3−1 0

)./

(8 04 2

)=

(.25 NaN−.25 0

)Note that NaN stands for not a number, and is produced by undefined arithmetic operations(such as division by zero).

The shape of an array can be changed using the reshape() command. The elements of theinput array are copied into the output array, so both arrays must have the same number ofelements (that is, the product of their row and column dimensions must be the same). Theinput array is read column-wise from left to right, and the output array is filled in the sameway.

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

%% Assigns [1; 3; 5; 7; 2; 4; 6; 8] to B.

B = reshape(A, 8, 1);

%% Assigns [1, 3, 5, 7, 2, 4, 6, 8] to B.

B = reshape(A, 1, 8);

%% Assigns [1, 5, 2, 6; 3, 7, 4, 8] to B.

B = reshape(A, 2, 4);

6. Some useful built-in vector and array functionsA function in Octave is a command that takes arguments and returns a value. For example,the sum() function calculates the sum of all values in a vector:

A = [2,3,1,-1];

%% Assigns the value 5 to b.

b = sum(A);

8

Page 9: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

An element-wise function manipulates each element of an array individually, and returns anarray of the same shape. For example, the abs() function, given the argument(

3 2 −1 0−1 2 −3 −1

)returns (

3 2 1 01 2 3 1

).

The following are some useful element-wise functions:

A = [3.2, -1.1, 0.1; -4.3, 0.3, -9; 11.6, -5.4, -4.2];

%% Assigns [3.2, 1.1, 0.1; 4.3, 0.3, 9; 11.6, 5.4, 4.2] to B.

B = abs(A);

%% Assigns [3, -1, 0; -4, 0, -9, 12, -5, -4] to B.

B = round(A);

%% Assigns [3, -2, 0; -5, 0, -9; 11, -6, -5] to B.

B = floor(A);

%% Assigns [4, -1, 1; -4, 1, -9; 12, -5, -4] to B.

B = ceil(A);

Transcendental functions like sin(), exp(), log(), and sqrt() act element-wise on arraysin the obvious way.

Many other functions convert vectors to scalars and arrays to vectors. For example, thesum() function described above converts a vector to a scalar by summing the values inthe vector. When given an array as an argument, these functions do not simply treat allthe values in the array as if they belong to a vector. Instead, each column of the array isprocessed separately as a vector. For example, if A is an array, then sum(A) is a row vectorcontaining the column sums of A. If you want the sum of everything in A, apply sum twice:sum(sum(A)).

The following are some useful functions of this type.

sum(). Computes the sum of the elements.

A = [3,1,2; 5,9,11; 0, 1, 1];

%% Assigns [8, 11, 14] to b.

b = sum(A);

9

Page 10: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

%% Assigns [6, 25, 2] to c.

c = sum(A’);

%% Assigns 33 to d.

d = sum(sum(A));

mean() Computes the average of the elements.

A = [3,1,2; 5,9,11; 0, 1, 1];

%% Assigns [2.66, 3.66,4.66] to b.

b = mean(A);

%% Assigns [2, 8.33, 0.66] to c.

c = mean(A’);

%% Assigns 11 to d.

d = mean(mean(A));

prod() Computes the product of the elements.

A = [3,1,2; 5,9,11; 0, 1, 1];

%% Assigns [0, 9, 22] to b.

b = prod(A);

%% Assigns [6, 495, 0] to c.

c = prod(A’);

%% Assigns 0 to d.

d = prod(prod(A));

max() Computes the largest element.

A = [3,1,2; 5,9,11; 0, 1, 1];

%% Assigns [5, 9, 11] to b.

b = max(A);

%% Assigns [3, 11, 1] to c.

c = max(A’);

%% Assigns 11 to d.

d = max(max(A));

10

Page 11: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

min() Computes the smallest element.

A = [3,1,2; 5,9,11; 0, 1, 1];

%% Assigns [0, 1, 1] to b.

b = min(A);

%% Assigns [1, 5, 0] to c.

c = min(A’);

%% Assigns 0 to d.

d = min(min(A));

7. Array SlicesOne of the most common operations on arrays is slicing, which means extracting a subarray.There are three ways that this can be accomplished:

1. A contiguous subarray can be obtained using the colon operator:

%% Assign a 3x4 array to A.

A = [2,3,4,5; 3,4,5,6; 9,8,7,6];

%% Assign [3, 4, 5, 6] to B.

B = A(2,:);

After the above statement, B is assigned the second (bolded) row of A:

2 3 4 53 4 5 69 8 7 6

%% Assign [4; 5; 7] to B.

B = A(:,3);

After the above statement, B is assigned the third (bolded) column of A:

2 3 4 53 4 5 69 8 7 6

%% Assign [5, 6; 7, 6] to B.

B = A(2:3,3:4);

11

Page 12: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

After the above statement, B is assigned the bolded 2× 2 subarray of A:

2 3 4 53 4 5 69 8 7 6

2. A regular non-contiguous subarray can be obtained using a stride:

%% Create a 2x5 array.

A = [9,8,7,6,5; 1,3,5,7,9];

%% Assign [9, 7, 5; 1, 5, 9] to B.

B = A(:,1:2:5);

After the above statement, B is assigned the bolded 2× 3 subarray of A:

(9 8 7 6 51 3 5 7 9

)

Note that when the stride is not present it defaults to 1.

3. A non-contiguous subarray can be obtained using an index vector. An index vector isa list of the indices that will make up the rows and columns of the new array.

%% Create a 6x3 array.

A = [1,2,1; 4,3,7; 6,7,4; 4,8,9; 2,9,5; 5,2,0];

%% An index vector.

ix = [3, 4, 1, 1];

%% Assigns [6,7,4; 4,8,9; 1,2,1; 1,2,1] to B.

B = A(ix,:);

After the above statement, the values of A and B are as follows:

A =

1 2 14 3 76 7 44 8 92 9 55 2 0

B =

6 7 44 8 91 2 11 2 1

12

Page 13: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

%% Another index vector.

iy = [3, 1];

%% Assigns [1,1; 7,4; 4,6; 9,4; 5,2; 0,5] to B.

B = A(:,iy);

After the above statement, the values of A and B are as follows:

A =

1 2 14 3 76 7 44 8 92 9 55 2 0

B =

1 17 44 69 45 20 5

%% Assigns [4,6; 9,4; 1,1; 1,1] to B.

B = A(ix,iy);

After the above statement, the values of A and B are as follows:

A =

1 2 14 3 76 7 44 8 92 9 55 2 0

B =

4 69 41 11 1

8. Conditional executionA block of commands can be executed conditionally using the if statement. All code betweenthe if and the matching end is executed only if the expression following the if is true. Forexample, the following program generates a uniform random integer on 1, 2, . . . , 10, andprints “u is even” only if the value is even:

u = ceil(10*rand(1,1));

%% rem(a, b) is the remainder upon dividing a by b.

if (rem(u, 2) == 0)

disp(’u is even’);

end

Multiple conditions can be checked using the else and elsif statements.

13

Page 14: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

%% Generate a uniform random number on (0,1).

u = rand(1,1);

if (u < .3)

disp(’The random number is less than .3’);

elsif (u < .6)

disp(’The random number is less than .6 but greater than or equal to .3’);

else

disp(’The random number is less than 1 but greater than or equal to .6’);

end

Your code will be much more clear if you indent the statements inside the if block. InMatlab if blocks are always closed by the end statement. In Octave you may use eitherend or endif for this purpose. It is usually clearer to use endif.

9. LoopsA loop is a block of statements that may be executed multiple times. In contrast, allstatements in an Octave program not contained in a loop are executed sequentially from topto bottom. Each passage through a loop is called an iteration.

Octave implements loops using for and while. A loop is constructed by enclosing one ormore statements between for and end or between while and end, as follows.

for i=1:10

statement 1

statement 2

...

end

or

while (1)

statement 1

statement 2

...

end

The statements inside a loop can be any legal code. In Octave you may close a for loopwith endfor and close a while loop with endwhile. In Matlab, all loops are closed withend. When using Octave, it is slightly clearer to use endfor and endwhile, but you areallowed to use simply end. Your code will be much more clear if you indent the statementsinside a while or for block, as above. This highlights the statements that may be executedmultiple times.

A while loop loops indefinitely until a condition becomes true. For example, the followingprogram draws uniform random numbers on the interval (0,1) until a value greater than

14

Page 15: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

or equal to 0.99 is drawn. At that point, the program stops and prints two numbers: therandom value that exceeded 0.99, and the number of draws that took place before that valueoccurred.

a = 0;

i = 0;

while (a < .99)

a = rand(1,1);

i = i+1;

end

disp(a);

disp(i);

The break statement can be used to exit a loop immediately. The following code is equivalentto the previous code.

ii = 0;

while (1)

a = rand(1,1);

ii = ii+1;

if (a >= .99)

break;

end

end

disp(a);

disp(ii);

The continue statement returns to the top of the block, skipping any subsequent statementsin the block. The following code indefinitely prints uniform random numbers between .99and 1.

15

Page 16: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

while (1)

a = rand(1,1);

if (a < .99)

continue;

end

disp(a);

end

A for loop executes a fixed number of times, and keeps track of the iterations by incrementinga counter variable, or index variable, that ranges over a set of values. The counter variableis i in the following example, and the range 1:23 specifies the values that are taken on byi.

for j=1:23

disp(sprintf(’The value of the counter variable is %i.’, j));

end

Note the use of the sprintf() function. The value of the variable i is interpolated intothe string where the %i symbol occurs. The %i symbol indicates that the value should beformated as an integer. The i in %i stands for integer.

As with array indices, a stride can be used with a for loop:

for j=1:4:40

disp(sprintf(’The value of the counter variable is %i.’, j));

end

It is also possible to loop over an arbitrary set of values contained in a row vector:

V = [1, 3, 2, 9, -1, 0, 0];

for i=V

disp(sprintf(’i=%i\ti^2=%i’, i, i^2));

end

Note that sprintf() now interpolates two values. The value of i is interpolated for the firstoccurrence of %i, and the value of i 2 is interpolated for the second occurrence of %i.

Also note that it is important that the index set (V in the above example) is a row vector.If it is a column vector, then the loop will only execute one time, with the counter variabletaking on the value of the entire column vector.

16

Page 17: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

10. Boolean operators and functionsBoolean operators return a true or a false value. In Octave, true is represented by 1 andfalse is represented by 0. Three basic Boolean operators are and (&), or (|), and not (!).These are usually used together with the arithmetic comparison operators == (equals), <(less than), > (greater than), <= (less than or equal to), >= (greater than or equal to):

%% Returns true.

b = ((1 == 0) | (3 == 2+1));

%% Returns false.

b = ((6*5 == 30) & (11 == 12-2));

%% Returns true.

b = ((11 < 5*3) & (30 >= 6*5));

All computer languages must make a distinction between assignment (setting the value of avariable), and testing equality (a Boolean function). Unfortunately, = is the natural symbolto use for both roles. In Octave, like FORTRAN, C, Perl, and many other languages, = isused for assignment, and == (double equals) is used for testing equality.

%% Set the value of x to 5.

x = 5;

%% Set the value of a to 0.

a = (x == 4);

%% Set the value of b to 1.

b = (x == 5);

Mistakenly writing = when == is intended is one of the most common errors, and can bedifficult to spot. Unfortunately it is usually a silent error, as the code is syntactically correctwith either symbol, but the meaning and results are changed.

Octave extends the scalar Boolean operators to arrays by applying the scalar operators toeach component of the array. The result is called an indicator array.

x = [2,4,3,6,5,8,1];

%% Assigns the value [0, 0, 0, 1, 1, 1, 0] to b.

b = (x >= 5);

%% Assigns the value [0, 0, 1, 0, 0, 0, 0] to b.

b = (x == 3);

By summing the result of a vector comparison, we can determine the number of elements ina vector that satisfy a given condition.

17

Page 18: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

x = [2,4,3,6,5,8,1];

%% Assigns the value 3 to b.

b = sum(x >= 5);

%% Assigns the value 1 to b.

b = sum(x == 3);

The Boolean functions isinf() and isnan() can be used to determine which values in anarray are infinity or NaN.

v = [0, 1, 0, 2, 0, 3, -1, 0];

w = [1, 0, 0, -1, 3, 0, 1, 4];

%% Returns [0, Inf, Nan, -2, 0, Inf, -1, 0].

u = v./w;

%% Returns [0, 1, 0, 0, 0, 1, 0, 0].

i1 = isinf(u);

%% Returns [0, 0, 1, 0, 0, 0, 0, 0].

i2 = isnan(u);

A list of the indices corresponding to the true values in an array can be obtained using thefind() function. These lists are often subsequently used as indices to extract the subvectorof elements where a certain condition is true.

v = [1, 0, 1, 1, 0, 0, 1];

%% Assigns [1, 3, 4, 7] to ix.

ix = find(v);

w = [3, -1, 0, 2, 8, 4];

%% Assigns [2, 3, 4] to ix.

ix = find(w < 3);

%% Assigns [-1, 0, 2] to b.

b = w(ix);

%% This combines the previous two lines into one statement.

b = w(find(w < 3));

18

Page 19: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

11. Operations on setsA set in Octave is a collection of distinct values (note that this is different from the usualdefinition of a set in which it is not required that the values are distinct). In contrast to avector, a set is not considered to be ordered. A vector in Octave can be used to represent aset, in which case the elements are always sorted.

The Octave function create set() constructs a set from the elements of a vector (thisfunction is called unique() in Matlab). It extracts the distinct elements from the vectorand sorts them.

V = [1, 3, 2, 2, 6, 4, 3, 9, 9];

%% Assigns [1, 2, 3, 4, 6, 9] to S.

S = create_set(V);

The function union() constructs the union of two sets.

V = [1, 2, 3];

W = [2, 3, 4];

%% Assigns [1, 2, 3, 4] to U.

U = union(V, W);

The function intersection() constructs the intersection of two sets (this function is calledintersect() in Matlab).

V = [1, 2, 3];

W = [2, 3, 4];

%% Assigns [2, 3] to I.

I = intersection(V, W);

The function complement() constructs the set consisting of the complement of the firstargument in the second argument.

V = [1, 2, 3, 4, 5];

W = [2, 3, 5];

%% Assigns [1, 4] to C.

C = complement(W, V);

In Matlab you must use setdiff() rather than complement(). Note that the order of thearguments is reversed.

19

Page 20: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

V = [1, 2, 3, 4, 5];

W = [2, 3, 5];

%% Assigns [1, 4] to C.

C = setdiff(V, W);

12. SortingA vector can be sorted in ascending order using the sort function:

x = [1,3,2,5,4,6,7];

%% Assigns [1, 2, 3, 4, 5, 6, 7] to y.

y = sort(x);

To sort in descending order, multiply the list by −1, sort it, then multiply the result by −1:

x = [1,3,2,5,4,6,7];

%% Assigns [7, 6, 5, 4, 3, 2, 1] to y.

y = -sort(-x);

Applying the sort function to an array sorts the columns:

A = [3, 2, 5; 1, 8, 0; 5, 5, 8; 2, 1, 9; 4, 5, 3];

%% Assigns [1, 1, 0; 2, 2, 3; 3, 5, 5; 4, 5, 8; 5, 8, 9] to B.

B = sort(A);

After the previous two statements, the values of A and B are as follows:

A =

3 2 51 8 05 5 82 1 94 5 3

B =

1 1 02 2 33 5 54 5 85 8 9

An indirect sort of x means that a list of indices ix are returned so that x(ix(1)),

x(ix(2)), ... is sorted. Using ix as a vector index, x(ix) is sorted.

x = [2,4,3,5,1,6,7];

%% Assigns [1, 2, 3, 4, 5, 6, 7] to a.

%% Assigns [5, 1, 3, 2, 4, 6, 7] to ix.

[a, ix] = sort(x);

20

Page 21: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

Indirect sorts can be used to sort an array according to the values in a single column.

x = [1,2;4,5;2,8;1,7;3,2;0,6];

[a,ix] = sort(x(:,2));

%% Assigns [1, 2; 3, 2; 4, 5; 0, 6; 1, 7; 2, 8] to x.

x = x(ix,:);

x =

1 24 52 81 73 20 6

x(ix, :) =

1 23 24 50 61 72 8

13. Defining new functionsThe Octave language can be extended by defining new functions. Suppose we want to definea function called step(x) so that step(x) = -1 if x < 0, step(x) = 0 if 0 ≤ x ≤ 10, andstep(x) = 1 if x > 10. The following code defines such a function.

%% Returns -1 if x < 0, returns 0 if x >= 0 and x <= 10, returns

%% 1 if x > 10.

function u = step(x)

if (x < 0)

u = -1;

elseif (x <= 10)

u = 0;

else u = 1;

end

Once this function has been defined, it can be called as if it were a built-in function.

%% Assigns the value 0 to a.

a = step(3);

%% Assigns the value 1 to b.

b = step(829);

14. Compatibility with MatlabAlmost everything in this document applies equally to Matlab and Octave. However inmany areas not described by this document (such as graphics), Matlab and Octave are quitedifferent.

To review, here are the key differences between Matlab syntax and Octave syntax:

21

Page 22: Octave: Overview for Statistical Computingdept.stat.lsa.umich.edu/.../Notes/octave_overview.pdf · 2005-09-04 · Octave: Overview for Statistical Computing Kerby Shedden Department

1. Matlab only accepts % as a comment character. Usage of # as a comment character isspecific to Octave.

2. Blocks opening with while, for, and if all must close with end in Matlab. In Octave,you may close these blocks with end if you wish, but it is more clear to close themwith endwhile, endfor, and endif, respectively.

3. In Matlab, the Boolean inequality symbol is ˜=. In Octave, either ˜= or != may beused.

4. Syntax for set operations such as complements and intersections is mostly differentbetween Matlab and Octave.

22