lettura simple

How to change a value in an array in Octave

In this lesson I'll explain how you change a value of a single element in an array without changing the other elements in Octave.

I'll give you a practical example.

Create an array of 5 elements.

>> v=[1 2 3 4 5]
v =
1 2 3 4 5

The first element of an array has index one v(1)=1 in Octave.

The second has two index v(2)=2 and so on.

$$ v(1) = 1 \\ v(2) = 2 \\ v(3) = 3 \\ v(4)=4 \\ v(5)=5 $$

To change the value of the first element of the array, type v(1)=6

>> v(1)=6

Now in the first place of the array there is the new value 6

>> v
v =
6 2 3 4 5

Note. When you modify an element of the array, the new value overwrites the previous one. Hence, you cannot retrieve the old value of the item after the modification.

Now edit the second element of the array by typing v(2)=7

>> v(2)=7

The value 7 is written in the second place of the array.

>> v
v =
6 7 3 4 5

You can change the value of any element of the array while leaving the other elements unchanged.

Now create an array with two indices (matrix)

>> M = [ 1 2 3 4; 5 6 7 8]
M =
1 2 3 4
5 6 7 8

In this case to change the value of an element of the array you have to indicate two indices of the element.

For example, to change the first item in the first row type M(1,1)=6

>> M(1,1)=6

You have to write the indices separated by a comma in brackets.

  • The first index is the row number of the element.
  • The second index is the column number of the element.

This command writes the value 6 in the first element of the first row of the array.

M =
6 2 3 4
5 6 7 8

Now change the third value in the second row of the matrix.

Type M(2,3)=-1

>> M(2,3)=-1

The first parameter (2) indicates the second row of the matrix and the second parameter (3) indicates the third column of the matrix.

Octave writes the value -1 to the element at position (2,3) of the array.

M =
6 2 3 4
5 6 -1 8

This way you can access and modify the elements of any multidimensional array.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin