Matrix Operations in Mma

*To*: mathgroup at yoda.physics.unc.edu*Subject*: Matrix Operations in Mma*From*: Count Dracula <lk3a at kelvin.seas.virginia.edu>*Date*: Sun, 3 Oct 1993 22:42:47 -0400

In response to Martin Rickli who writes >> How can I assign a matrix to a part of another matrix? I have below two modules, assign2 and assign3, with identical input arguments: A = the larger matrix which will have parts of it reassigned alist = the smaller matrix which will be inserted into A begrow = the number of the first row in A where elements from alist will be inserted begcol = the number of the first column in A where elements from alist will be inserted The difference between the modules is that assign2 creates a new matrix and uses ReplacePart while assign3 changes the matrix A in the right places without forming another matrix. Here's a test program to compare results and times ________________________________________________________________________________ A = IdentityMatrix[90] B = A row = {a, b, c, d, e, f, g, P, Q, R} alist = Array[ row &, 50 ] assign2[A_, alist_, begrow_, begcol_] := Module[{ rows, cols, index, flist }, rows = Range[begrow, begrow + Length[alist] - 1]; cols = Range[begcol, begcol + Length[ alist[[1]] ] - 1]; index = Flatten[ Outer[ List, rows, cols ], 1 ]; flist = Transpose[ {Flatten[alist], index} ]; Fold[ ReplacePart[#1, Sequence @@ #2] &, A, flist ] ] Attributes[assign3] = {HoldFirst} assign3[A_, alist_, begrow_, begcol_] := Module[{ rows, cols, index, flist }, rows = Range[begrow, begrow + Length[alist] - 1]; cols = Range[begcol, begcol + Length[ alist[[1]] ] - 1]; index = Flatten[ Outer[ List, rows, cols ], 1 ]; flist = Transpose[ Append[ Transpose[index],Flatten[alist] ] ]; Apply[(A[[#1, #2]] = #3) & , flist, 1]; Null ] t2 = Timing[A = assign2[A, alist, 2, 3]]; t3 = Timing[assign3[B, alist, 2, 3]]; { t2[[1]], t3[[1]], A==B } ________________________________________________________________________________ This test program with Version 2.2 on an RS6000 gives Out[1]= {1.06 Second, 0.24 Second, True} and in all other tests, with some other modules, assign3 reported the least time. It is of course somewhat Fortran-like in its final line. I would like to hear from people who have suggestions for improvement. Levent lk3a at kelvin.seas.virginia.edu