MathGroup Archive 1993

[Date Index] [Thread Index] [Author Index]

Search the Archive

Matrix Operations in Mma

  • To: mathgroup at yoda.physics.unc.edu
  • Subject: Matrix Operations in Mma
  • From: Mark E. Fisher <m1mef00 at frb.gov>
  • Date: Fri, 08 Oct 93 10:59:48 -0400

Following up on

>> How can I assign a matrix to a part of another matrix

Here is a one-liner, preceded by an easier to read, broken-up version with
some error checking built in:
---------------------------------------------------------------------------
(* code to insert tabA (smaller matrix) into slotB (larger matrix) *)
MatrixInsert::usage = "MartixInsert[tabA, slotB, {row, col}] inserts tabA into
slotB at position {row, col}."
MatrixInsert::willnotfit = "`1` will not fit in `2` at position {`3`, `4`}"

MatrixInsert[tabA:{_List ..}, slotB:{_List ..}, 
		{row_Integer?Positive, col_Integer?Positive}] := 
	Module[{tabrow, tabcol, takerows, newrows},
	{tabrow, tabcol} = Dimensions[tabA];
	(* check bounds *)
	If[And @@ Thread[{row, col} + {tabrow, tabcol} <= Dimensions[slotB] + 1],
	(* get rows to be changed *)
	takerows = Take[slotB, {row, row + tabrow - 1}];
	(* drop old column entries and insert new column entries *)
	newrows = MapThread[MapAt[Apply[Sequence, #]&, 
					(* remove outer List from new cols *)
		Insert[Drop[#1, {col, col + tabcol - 1}], #2, col], col]&,
			{takerows, tabA}];
	(* drop old rows and insert new rows *)
	MapAt[Apply[Sequence, #]&, (* remove outer List from new rows *)
		Insert[Drop[slotB, {row, row + tabrow - 1}], newrows, row], row],
	(* else, bad bounds *)
	Message[MatrixInsert::willnotfit, tabA, slotB, row, col]]]

(* all in one line, but less clear *)
MatrixInsertOneLiner[tabA_, slotB_, {row_, col_}] :=
	With[{tabrow = Length[tabA], tabcol = Length[First[tabA]]},
	MapAt[Apply[Sequence, #]&, 
		Insert[Drop[slotB, {row, row + tabrow - 1}], 
			MapThread[
				MapAt[Apply[Sequence, #]&, 
					Insert[Drop[#1, {col, col +
tabcol - 1}], #2, 
					col], 
				col]&,
			{Take[slotB, {row, row + tabrow - 1}], tabA}], 
		row], 
	row]]
---------------------------------------------------------------------------
Example:
tabA = Array[a, {4, 4}]
slotB = Array[b, {7, 7}]
MatrixInsert[tabA, slotB, {2, 3}]


Mark Fisher
Trading Risk Analysis
Federal Reserve Board
mfisher at frb.gov





  • Prev by Date: Re: problem with init.m in mma 2.2 on RS/6000 and TeX/Mathematica
  • Next by Date: Re: Help: how to disp. 3-D vectors
  • Previous by thread: Matrix Operations in Mma
  • Next by thread: Re: Matrix Operations in Mma