Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

Interacting with GNU Octave: Variables

Save for later
  • 480 min read
  • 2011-06-17 00:00:00

article-image

GNU Octave Beginner's Guide


interacting-gnu-octave-variables-img-0

Become a proficient Octave user by learning this high-level scientific numerical tool from the ground up

        

In the following, we shall see how to instantiate simple variables. By simple variables, we mean scalars, vectors, and matrices. First, a scalar variable with name a is assigned the value 1 by the command:

octave:1> a=1


a = 1



That is, you write the variable name, in this case a, and then you assign a value to the variable using the equal sign. Note that in Octave, variables are not instantiated with a type specifier as it is known from C and other lower-level languages. Octave interprets a number as a real number unless you explicitly tell it otherwise.

In Octave, a real number is a double-precision, floating-point number,which means that the number is accurate within the first 15 digits. Single precision is accurate within the first 6 digits.


You can display the value of a variable simply by typing the variable name:

octave:2>a


a = 1



Let us move on and instantiate an array of numbers:

octave:3 > b = [1 2 3]


b =
1 2 3



Octave interprets this as the row vector:

interacting-gnu-octave-variables-img-1


rather than a simple one-dimensional array. The elements (or the entries) in a row vector can also be separated by commas, so the command above could have been:

octave:3> b = [1, 2, 3]


b =
1 2 3



To instantiate a column vector:

interacting-gnu-octave-variables-img-2


you can use:

octave:4 > c = [1;2;3]


c =
1
2
3



Notice how each row is separated by a semicolon.

We now move on and instantiate a matrix with two rows and three columns (a 2 x 3 matrix):

interacting-gnu-octave-variables-img-3


using the following command:

octave:5 > A = [1 2 3; 4 5 6]


A =
1 2 3
4 5 6



Notice that I use uppercase letters for matrix variables and lowercase letters for scalars and vectors, but this is, of course, a matter of preference, and Octave has no guidelines in this respect. It is important to note, however, that in Octave there is a difference between upper and lowercase letters. If we had used a lowercase a in Command 5 above, Octave would have overwritten the already existing variable instantiated in Command 1. Whenever you assign a new value to an existing variable, the old value is no longer accessible, so be very careful whenever reassigning new values to variables.


Variable names can be composed of characters, underscores, and numbers. A variable name cannot begin with a number. For example, a_1 is accepted as a valid variable name, but 1_a is not.

In this article, we shall use the more general term array when referring to a vector or a matrix variable.

Accessing and changing array elements


To access the second element in the row vector b, we use parenthesis:

octave:6 > b(2)


ans = 2



That is, the array indices start from 1. This is an abbreviation for "answer" and is a variable in itself with a value, which is 2 in the above example.

For the matrix variable A, we use, for example:

octave:7> A(2,3)


ans = 6



to access the element in the second row and the third column. You can access entire rows and columns by using a colon:

octave:8> A(:,2)


ans =
2
5

octave:9 > A(1,:)

ans =
1 2 3



Now that we know how to access the elements in vectors and matrices, we can change the values of these elements as well. To try to set the element A(2,3)to -10.1:

octave:10 > A(2,3) = -10.1


A =
1.0000 2.0000 3.0000
4.0000 5.0000 -10.1000



Since one of the elements in A is now a non-integer number, all elements are shown in floating point format. The number of displayed digits can change depending on the default value, but for Octave's interpreter there is no difference—it always uses double precision for all calculations unless you explicitly tell it not to.


You can change the displayed format using format short or format long. The default is format short.

It is also possible to change the values of all the elements in an entire row by using the colon operator. For example, to substitute the second row in the matrix A with the vector b (from Command 3 above), we use:

octave:11 > A(2,:) = b


A =
1 2 3
1 2 3

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at ₹800/month. Cancel anytime


This substitution is valid because the vector b has the same number of elements as the rows in A. Let us try to mess things up on purpose and replace the second column in A with b:

octave:12 > A(:,2) = b


error: A(I,J,...) = X: dimension mismatch



Here Octave prints an error message telling us that the dimensions do not match because we wanted to substitute three numbers into an array with just two elements. Furthermore, b is a row vector, and we cannot replace a column with a row.

Always read the error messages that Octave prints out. Usually they are very helpful.


There is an exception to the dimension mismatch shown above. You can always replace elements, entire rows, and columns with a scalar like this:

octave:13> A(:,2) = 42


A =
1 42 3
1 42 3


More examples


It is possible to delete elements, entire rows, and columns, extend existing arrays, and much more.

Time for action – manipulating arrays

  1. To delete the second column in A, we use:

    octave:14> A(:,2) = []


    A =
    1 3
    1 3

    
    

  2. We can extend an existing array, for example:

    octave:15 > b = [b 4 5]


    b =
    1 2 3 4 5

    
    

  3. Finally, try the following commands:

    octave:16> d = [2 4 6 8 10 12 14 16 18 20]


    d =
    2 4 6 8 10 12 14 16 18 20

    octave:17> d(1:2:9)

    ans =
    2 6 10 14 18

    octave:18> d(3:3:12) = -1

    d =
    2 4 -1 8 10 -1 14 16 -1 20 0 -1

    
    

What just happened?


In Command 14, Octave interprets [] as an empty column vector and column 2 in A is then deleted in the command. Instead of deleting a column, we could have deleted a row, for example as an empty column vector and column 2 in A is then deleted in the command.

octave:14> A(2,:)=[]




On the right-hand side of the equal sign in Command 15, we have constructed a new vector given by [b 4 5], that is, if we write out b, we get [1 2 3 4 5] since b=[1 2 3]. Because of the equal sign, we assign the variable b to this vector and delete the existing value of b. Of course, we cannot extend b using b=[b; 4; 5] since this attempts to augment a column vector onto a row vector.

Octave first evaluates the right-hand side of the equal sign and then assigns that result to the variable on the left-hand side. The right-hand side is named an expression.


In Command 16, we instantiated a row vector d, and in Command 17, we accessed the elements with indices 1,3,5,7, and 9, that is, every second element starting from 1. Command 18 could have made you a bit concerned! d is a row vector with 10 elements, but the command instructs Octave to enter the value -1 into elements 3, 6, 9 and 12, that is, into an element that does not exist. In such cases, Octave automatically extends the vector (or array in general) and sets the value of the added elements to zero unless you instruct it to set a specific value. In Command 18, we only instructed Octave to set element 12 to -1, and the value of element 11 will therefore be given the default value 0 as seen from the output. In low-level programming languages, accessing non-existing or non-allocated array elements may result in a program crash the first time it is running2.

This will be the best case scenario. In a worse scenario, the program will work for years, but then crash all of a sudden, which is rather unfortunate if it controls a nuclear power plant or a space shuttle.

As you can see, Octave is designed to work in a vectorized manner. It is therefore often referred to as a vectorized programming language.


Complex variables


Octave also supports calculations with complex numbers. As you may recall, a complex number can be written as z = a + bi, where a is the real part, b is the imaginary part, and i is the imaginary unit defined from i2 = –49491.

To instantiate a complex variable, say z = 1 + 2i, you can type:

octave:19> z = 1 + 2I


z = 1 + 2i



When Octave starts, the variables i, j, I, and J are all imaginary units, so you can use either one of them. I prefer using I for the imaginary unit, since i and j are often used as indices and J is not usually used to symbolize i.

To retrieve the real and imaginary parts of a complex number, you use:

octave:20> real(z)


ans = 1

octave:21>imag(z)

ans = 2



You can also instantiate complex vectors and matrices, for example:

octave:22> Z = [1 -2.3I; 4I 5+6.7I]


Z =
1.0000 + 0.0000i 0.0000 - 2.3000i
0.0000 + 4.0000i 5.0000 + 6.7000i



Be careful! If an array element has non-zero real and imaginary parts, do not leave any blanks (space characters) between the two parts. For example, had we used Z=[1 -2.3I; 4I 5 + 6.7I] in Command 22, the last element would be interpreted as two separate elements (5 and 6.7i). This would lead to dimension mismatch.

The elements in complex arrays can be accessed in the same way as we have done for arrays composed of real numbers. You can use real(Z) and imag(Z) to print the real and imaginary parts of the complex array Z. (Try it out!)