How to | Update Parts of a Matrix
The Wolfram Language has many matrix operations that support operations such as building, computing, and visualizing matrices. It also has a rich language for picking out parts of matrices and assigning new values to them.
mat = Table[Subscript[m, i, j], {i, 5}, {j, 5}];
mat//MatrixFormUse [[...]] (the short form of Part) on the left-hand side of an assignment to set an element:
mat[[1, 2]] = xThis shows that the element at position (1, 2) has been updated:
mat//MatrixFormTo set an entire row, use one index to specify the row and assign it to the new row:
mat[[4]] = {1, 2, 3, 4, 5};
mat//MatrixFormTo set an entire column, select all rows with All and specify the column:
mat[[All, 4]] = {a, b, c, d, e};
mat//MatrixFormTo set a submatrix you can use the short form of Span (;;).
First set up a 5×5 matrix of random integers between 0 and 10:
mat = RandomInteger[10, {5, 5}];
mat//MatrixFormThe top-left 3×4 matrix highlighted here corresponds to rows 1 through 3 and columns 1 through 4:
Update the highlighted submatrix by using the short form of Span (;;) to specify the relevant span of rows and columns:
mat[[1 ;; 3, 1 ;; 4]] = {{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}};
mat//MatrixFormUpdate all elements except the outermost rows and columns (negative indices count from the end):
mat[[2 ;; -2, 2 ;; -2]] = {{-1, -1, -1}, {-1, -1, -1}, {-1, -1, -1}};
mat//MatrixFormWhen you update a large matrix you should try to avoid doing this in a loop. If you can use one of the updating techniques to update all elements in one command, this will typically be much faster:
mat = RandomReal[10, {5000, 5000}];This is a slow way to update every element in a row:
Do[mat[[i, 1]] = 0.0, {i, 1, 5000}];//AbsoluteTimingmat[[All, 1]] = 0.0;//AbsoluteTimingIf you cannot avoid updating a matrix in a loop, you need to take care to avoid extra references to the matrix. Otherwise the matrix will be copied and the loop will not run very fast:
mat = RandomReal[10, {1000, 1000}];This takes care to avoid extra references. The loop runs quite fast:
Do[mat[[i, i + 1]] = 0.0, {i, 999}];//AbsoluteTimingThis makes a copy of the matrix at every step, and the loop does not run very fast:
Do[b = mat;mat[[i, i + 1]] = 0.0, {i, 999}];//AbsoluteTiming