Part

Part has a powerful features that many users aren't aware of. In the next cell a matrix (m) is made and used in some examples below. Of course the method demonstrated below can be used on any expression not only matrices. To make the examples below easy to understand m[[i,j]] is simply `x` followed by integers i and j.

Clear[m,x11,x12,x13,x14,x15,x21,x22,x23,x24,x25,x31,x32,x33,x34,x35,x41,x42,x43,x44,x45,x51,x52,x53,x54,x55];&IndentingNewLine;m={{x11,x12,x13,x14,x15},{x21,x22,x23,x24,x25},{x31,x32,x33,x34,x35},{x41,x42,x43,x44,x45},{x51,x52,x53,x54,x55}};

m[[list1,list2]] returns the sub-matrix of (m) formed by the intersection of the rows given by list1 and the columns given by list2. The next cell gives an example. This is probably the quickest way to get such a submatrix of (m).

m[[{1,3,4},{2,5}]]

{{x12,x15},{x32,x35},{x42,x45}}

m[[n,list2]] returns a list of elements at positions (list2) in column n. The next cell gives an example.

m[[2,{1,2,5}]]

{x21,x22,x25}

Likewise m[[list1,n]] returns a list of elements at positions (list1) of column n. The next cell gives an example.

m[[{1,2,5},2]]

{x12,x22,x52}

Use of the forms demonstrated above gives the fastest way to change multiple parts of an expression provided the parts can be reached with this method. Rob Knapp makes this point in a tutorial on Packed Arrays at  
http://library.wolfram.com/tutorials/. In that tutorial he shows how this method gives a significant speed advantage in an implementation of LUDecomposition. This method of changing multiple values is demonstrated on simple examples in the cells below where elements of the matrix (m) from above are changed.

Notice the use of All inside Part is not available in Version 3 or earlier.

m[[All,3]]={1,1,1,1,1};MatrixForm[m]

[Graphics:../Images/Tricks_gr_125.gif]

m[[2,All]]={2,2,2,2,2};MatrixForm[m]

[Graphics:../Images/Tricks_gr_126.gif]

m[[{1,2,3},{2,3,4,5}]]={{0,0,0,0},{0,0,0,0},{0,0,0,0}};MatrixForm[m]

[Graphics:../Images/Tricks_gr_127.gif]


Back to Main Page...

Converted by Mathematica      May 19, 2000
Styles converted by a program by Reinhold Kainhofer ( reinhold@wolfram.com )