Octave array functions
Some predefined functions of Octave are dedicated to arrays and allow you to save a lot of time during calculation operations.
I'll give you some practical examples.
Create an array with five elements and assign it to a vector variable.
>> v = [ 1 4 2 6 3 ]
v =
1 4 2 6 3
Here are some array functions in Octave
sum()
Adds the elements in the array
>> sum(v)
ans = 16
Note. It is the algebraic sum of the numerical values in the array $$ 1 + 4 + 2 + 6 + 3 = 16 $$
prod()
Multiply all the elements of the array
>> prod(v)
ans = 144
Note. Calculates the product of the numeric elements in the array $$ 1 \cdot 4 \cdot 2 \cdot 6 \cdot 3 = 144 $$
length()
Find the number of elements in the array.
>> length(v)
ans = 5
Note. The array consists of five elements [ 1 4 2 6 3 ]
mean()
Calculates the arithmetic mean of the numeric elements of the array
>> mean(v)
ans = 3.2000
Note. The arithmetic mean of the elements of the array is equal to the sum of the elements divided by the number of elements in the array $$ \frac{1+4+2+6+3}{5} = \frac{16}{5} = 3.2 $$
max()
Find the maximum value in the elements of the array
>> max(v)
ans = 6
Note. The maximum value in the array [ 1 4 2 6 3 ] is six.
min()
Find the minimum value in the elements of the array
>> min(v)
ans = 1
Note. The minimum value in the array [ 1 4 2 6 3 ] is one.
find()
Finds elements of the array that satisfy a selection criterion.
This function returns the position of the elements in the array and not their value.
>> find(v>2)
ans =
2 4 5
Note. In this case the values greater than 2 in the array [ 1 4 2 6 3 ] are the elements in position 2, 4 and 5 i.e. the second, fourth and fifth element of the array.
sort()
Sort vector elements in ascending order
>> sort(v, 'ascend')
ans =
1 2 3 4 6
or descending order
>> sort(v, 'descend')
ans =
6 4 3 2 1
The second parameter is 'ascend' by default.
So, if you type sort(v) without specifying the second parameter, Octave sorts in ascending order.
>> sort(v)
ans =
1 2 3 4 6
round()
Rounds array elements to the nearest integer to the right or left of each number.
>> v = [ 0.2 -0.4 1.4 1.9 -2.1 ]
v =
0.20000 -0.40000 1.40000 1.90000 -2.10000
>> round(v)
ans =
0 -0 1 2 -2
fix()
Rounds array elements to the nearest integer to zero.
This function round to the right if the number is negative or to the left if the number is positive.
>> v = [ 0.2 -0.4 1.4 1.9 -2.1 ]
v =
0.20000 -0.40000 1.40000 1.90000 -2.10000
>> fix(v)
ans =
0 -0 1 1 -2
floor()
This function rounds array elements to the nearest integer to minus infinity (-∞) i.e. to the left of the number.
>> v = [ 0.2 -0.4 1.4 1.9 -2.1 ]
v =
0.20000 -0.40000 1.40000 1.90000 -2.10000
>> floor(v)
ans =
0 -1 1 1 -3
ceil()
Rounds array elements to the nearest integer to plus infinity (+∞) i.e. to the right of the number.
>> v = [ 0.2 -0.4 1.4 1.9 -2.1 ]
v =
0.20000 -0.40000 1.40000 1.90000 -2.10000
>> ceil(v)
ans =1 -0 2 2 -2