此为 Mathematica 7 文档,内容基于更早版本的 Wolfram 语言
查看最新文档(版本11.1)
Mathematica HowTo
How to | Update Parts of a Matrix
Mathematica 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.
Define the following matrix:
In[1]:=
Click for copyable input
Out[1]//MatrixForm=
Use [[...]] (the short form of Part) on the left-hand side of an assignment to set an element:
In[2]:=
Click for copyable input
Out[2]=
This shows that the element at position (1, 2) has been updated:
In[3]:=
Click for copyable input
Out[3]//MatrixForm=
To set an entire row, use one index to specify the row and assign it to the new row:
In[4]:=
Click for copyable input
Out[4]//MatrixForm=
To set an entire column, select all rows with All and specify the column:
In[5]:=
Click for copyable input
Out[5]//MatrixForm=
    
To 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:
In[6]:=
Click for copyable input
Out[6]//MatrixForm=
The top-left 3×4 matrix highlighted here corresponds to rows 1 through 3 and columns 1 through 4:
Out[7]=
Update the highlighted submatrix by using the short form ;; of Span to specify the relevant span of rows and columns:
In[8]:=
Click for copyable input
Out[8]//MatrixForm=
Update all elements except the outermost rows and columns (negative indices count from the end):
In[9]:=
Click for copyable input
Out[9]//MatrixForm=
    
When 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:
In[10]:=
Click for copyable input
This is a slow way to update every element in a row:
In[11]:=
Click for copyable input
Out[11]=
This is much faster:
In[12]:=
Click for copyable input
Out[12]=
If 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:
In[13]:=
Click for copyable input
This takes care to avoid extra references. The loop runs quite fast:
In[14]:=
Click for copyable input
Out[14]=
This makes a copy of the matrix at every step, and the loop does not run very fast:
In[15]:=
Click for copyable input
Out[15]=