Previous Up Next

5.48.5  Modify an element or row of a matrix assigned to a variable: ::=, =<

For named matrices, the elements can be changed by assignment. Recall the elements are indexed starting at 0, using double brackets allows you to use indices starting at 1.
Input:

A := [[1,2,3],[4,5,6]]

Output:

[[1,2,3],[4,5,6]]

Input:

A[0,2] := 7

then:

A

Output:

[[1,2,7],[4,5,6]]

Input:

A[[1,2]] := 9

then:

A

Output:

[[1,9,7],[4,5,6]]

When an element of a matrix is changed with the := assignment, a new copy of the matrix is created with the modified element. Particularly for large matrices, it is more efficient to use the =< assignment, which will change the element of the matrix without making a copy. For example, defining A as
Input:

A := [[4,5],[2,6]]

the following commands will all return the matrix A with the element in the second row, first column, changed to 3.
Input:

A[1,0] := 3

or:

A[1,0] =< 3

or:

A[[2,1]] := 3

or:

A[[2,1]] =< 3

then:

A

Output:

[[4,5],[3,6]]

Larger parts of a matrix can be changed simultaneously. Letting A := [[4,5],[2,6]] again, the following commands will change the second row to [3,7]
Input:

A[1] := [3,7]

or:

A[1] =< [3,7]

or:

A[[2]] := [3,7]

or:

A[[2]] =< [3,7]

The =< assignment must be used carefully, since it not only modifies a matrix A, it modifies all objects pointing to the matrix. In a program, initialization should contain a line like A := copy(B), so modifications done on A don’t affect B, and modifications done on B don’t affect A. For example,
Input:

B := [[4,5],[2,6]]

then:

A := B

or
Input:

A =< B

creates two matrices equal to [[4,5],[2,6]]. Then
Input:

A[1] =< [3,7]

or:

B[1] =< [3,7]

will transform both A and B to [[4,5],[3,7]]. On the other hand, creating A and B with
Input:

B := [[4,5],[2,6]]
A := copy(B)

will again create two matrices equal to [[4,5],[2,6]]. But
Input:

A[1] =< [3,7]

will change A to [[4,5],[3,7]], but B will still be [[4,5],[2,6]].


Previous Up Next