
Replace an array element in Matlab
In this lesson, I'll teach you how to modify the value of a single element in an array in Matlab without changing the other elements, using a practical example.
First, create an array consisting of 5 elements:
>> v=[1 2 3 4 5]
v =
1 2 3 4 5
In Matlab, the first element of an array occupies position one, i.e., v(1)=1 in the array index.
The second element occupies position two, i.e., v(2)=2, and so on:
$$ v(1) = 1 \\ v(2) = 2 \\ v(3) = 3 \\ v(4)=4 \\ v(5)=5 $$
To modify the value of the first element of the array, type the name of the array followed by the position of the element.
After the equal sign, write the value you want to assign to the array element:
>> v(1)=6
Now, display the content of the array.
>> v
v =
6 2 3 4 5
The new value of 6 you just assigned will replace the previous value of 1 in the array index.
Now modify the second element of the array. Type v(2)=7
>> v(2)=7
With this command, you assign the value 7 to the second position in the array index.
>> v
v =
6 7 3 4 5
You can modify any element of the array while leaving the other elements unchanged by following the same procedure.
The same applies to two-dimensional arrays or matrices.
For example, create a matrix, which is an array with two indices:
>> M = [ 1 2 3 4; 5 6 7 8]
M =
1 2 3 4
5 6 7 8
In the case of matrices, to modify an element's value, you must indicate both indices.
For example, to modify the first element in the first row, type M(1,1)=6
>> M(1,1)=6
Write the two indices inside parentheses, separated by a comma.
The first index is the row number of the element in the matrix, and the second index is the column number of the element in the matrix.
The M(1,1)=6 command assigns the value of 6 to the first element of the first row of the matrix
M =
6 2 3 4
5 6 7 8
Now, modify the third value in the second row of the matrix by typing M(2,3)=-1
>> M(2,3)=-1
This command assigns the value of -1 to the element located in the second row and third column of the matrix
M =
6 2 3 4
5 6 -1 8
Using this method, you can access and modify the value of any element, even in a multidimensional array.