Computers

Declare Variables in Octave

Declare Variables in Octave

In this tutorial, you will learn how to declare variables in Octave with examples. You can declare and use the variable name to assign the value and later use it in the script/function.

Declare Variables

We can use the variable name and the assignment operator to declare and instantiate the variable in Octave. We need to declare and define the variable before using it.

For example, if we try to use the variable x without defining it, we get the following error:

error: ‘x’ undefined near line <line_number>, column <col_number>

You can define and assign values to a variable before using it in the code to avoid such errors.

 

Undefined variable Octave Error

Examples

Let’s see some examples to declare and assign the value to the variable.

Scalars

A scalar is a simple number or numeric variable. The size of the scalar variable will be 1×1.

a = 25;

g = 9.81;

Note that Octave is case-sensitive. Variables with lowercase letters are different than the variables with the uppercase letters.

For example, the variables x and X are not the same.

Octave is case sensitive

In the example, the variable x is a number with 25 assigned to it. However, the variable X holds the string ‘Hello’.

Example

Assign a value of 10 to a variable called rate.

>> rate = 10;
>> rate

rate = 10

When we end the statement with a semicolon in the command window, Octave will suppress the output display.

If the semicolon is not used, the Octave will display the output. The format would be:

<variable_name> = <value>

We can type the variable name at the command prompt to know the variable’s value.

 

Declare variables in Octave

Vectors

Vectors can be either a row matrix(only one row) or a column vector (having only one column). The size of the row vector would be 1xn ( n columns). The size of the column vector would be nx1 ( n rows).

We can declare the values inside square brackets and elements separated by commas.

For example, to declare and instantiate a row vector:

x = [ 2 ,4, 6];

For example, to declare and instantiate a column vector:

y = [ 2 ;4 ;6];

Matrices

A matrix has multiple rows and columns. The size of the matrix would be mxn ( m rows and n columns and m,n > 1)

We can declare the values inside square brackets and rows separated by a semi-colon. Each element in the row can be separated by space or comma(,)

Built-in Constants

In Octave, we can use some built-in constants. There is no need to declare and initialize these variables.

pi

The pi constant is the ratio of the circumference of a circle to its diameter.

To know the variables defined in the current session:

https://www.testingdocs.com/octave-who-command/

Octave Tutorials

Octave Tutorial on this website can be found at: