此为 Mathematica 7 文档,内容基于更早版本的 Wolfram 语言
查看最新文档(版本11.1)
Mathematica 教程|函数 »

Getting and Setting Pieces of Matrices

m[[i,j]]the i, jth entry
m[[i]]the ith row
m[[All,i]]the ith column
Take[m,{i0,i1},{j0,j1}]the submatrix with rows i0 through i1 and columns j0 through j1
m[[i0;;i1,j0;;j1]]the submatrix with rows i0 through i1 and columns j0 through j1
m[[{i1,...,ir}, {j1, ... , js}]] the r×s submatrix with elements having row indices ik and column indices jk
Tr[m,List]elements on the diagonal
ArrayRules[m]positions of nonzero elements

Ways to get pieces of matrices.

Matrices in Mathematica are represented as lists of lists. You can use all the standard Mathematica list-manipulation operations on matrices.
Here is a sample 3×3 matrix.
In[1]:=
Click for copyable input
Out[1]=
This picks out the second row of the matrix.
In[2]:=
Click for copyable input
Out[2]=
Here is the second column of the matrix.
In[3]:=
Click for copyable input
Out[3]=
This picks out a submatrix.
In[4]:=
Click for copyable input
Out[4]=
m={{a11,a12,...},{a21,a22,...},...}assign m to be a matrix
m[[i,j]]=areset element {i, j} to be a
m[[i]]=areset all elements in row i to be a
m[[i]]={a1,a2,...}reset elements in row i to be {a1, a2, ...}
m[[i0;;i1]]={v1,v2,...}reset rows i0 through i1 to be vectors {v1, v2, ...}
m[[All,j]]=areset all elements in column j to be a
m[[All,j]]={a1,a2,...}reset elements in column j to be {a1, a2, ...}
m[[i0;;i1,j0;;j1]]={{a11,a12,...},{a21,a22,...},...}reset the submatrix with rows i0 through i1 and columns j0 through j1 to new values

Resetting parts of matrices.

Here is a 3×3 matrix.
In[5]:=
Click for copyable input
Out[5]=
This resets the 2, 2 element to be x, then shows the whole matrix.
In[6]:=
Click for copyable input
Out[6]=
This resets all elements in the second column to be z.
In[7]:=
Click for copyable input
Out[7]=
This separately resets the three elements in the second column.
In[8]:=
Click for copyable input
Out[8]=
This increments all the values in the second column.
In[9]:=
Click for copyable input
Out[9]=
A range of indices can be specified by using ;; (Span).
This resets the first two rows to be new vectors.
In[10]:=
Click for copyable input
Out[10]=
This resets elements in the first and third columns of each row.
In[11]:=
Click for copyable input
Out[11]=
This resets elements in the first and third columns of rows 2 through 3.
In[12]:=
Click for copyable input
Out[12]=