How to extract values from an array in Octave

In this guide I'll explain how to extract the values of an array by slicing with a practical example.

Make an array with seven values

>> v=[10 11 12 13 14 15 16]
v =
10 11 12 13 14 15 16

If you want to extract the first three values type b=v(1:3)

>> b=v(1:3)
b =
10 11 12

This command extracts the sequence of the first three values of array v and writes them to array b.

The first element of an array on Octave has the index equal to one.

Note. The colon symbol (:) separates the position of the first and last value you want to extract from the vector.

If instead you want to extract the third, fourth and fifth values of the array v type b=v(3:5)

>> b=v(3:5)
b =
12 13 14

If you want to extract the first, third and fifth values of the array v type b=v([1 3 5])

>> b=v([1 3 5])
b =
10 12 14

To extract two separate ranges, such as the first and second value and the sixth and seventh, type b=v([1:2 6:7])

>> b=v([1:2 6:7])
b =
10 11 15 16

To extract the last value from the array, type b=v(end)

>> b=v(end)
b = 16

The word end allows you to extract the last values of the array when you don't know the last inde

For example, to extract values from the fourth to the end of the array, type

>> b=v(4:end)
b =
13 14 15 16

To extract the last three values of the array type b=v(end-2:end)

>> b=v(end-2:end)
b =
14 15 16

To extract only odd-indexed values, type b=v(1:2:end)

The intermediate parameter (2) is the step that is the increment from one position in the array to the next.

>> b=v(1:2:end)
b =
10 12 14 16

The step can also be negative.

This way you can also reverse the order of the values in the array from last to first by typing b=v(end:-1:1)

>> b=v(end:-1:1)
b =
16 15 14 13 12 11 10

You can also replace the array values with other values.

For example, replace the first and second array values with 20 and 21 by typing v([1 2]) = [20 21]

>> v([1 2]) = [20 21]
v =
20 21 12 13 14 15 16

If you want to replace multiple values of the array with the same value.

For example, replace the first and second array values with 99 by typing v([1 2]) = 99

>> v([1 2]) = 99
v =
99 99 12 13 14 15 16

Slicing allows you to extract and modify the array quickly and easily.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin