MathGroup Archive 1997

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

Search the Archive

Re: Re: Replacing part of a matrix by another

  • To: mathgroup at smc.vnet.net
  • Subject: [mg5632] Re: [mg5621] Re: Replacing part of a matrix by another
  • From: Allan Hayes <hay at haystack.demon.co.uk>
  • Date: Wed, 1 Jan 1997 21:04:58 -0500
  • Sender: owner-wri-mathgroup at wolfram.com

Lee <killough at convex.com>
in [mg5621] Re: Replacing part of a matrix by another
gives the following function for replacing a submatrix of a matrix  
M by a matrix L starting at position pos.

SetAttributes[setsub,HoldFirst]
setsub[M_,L_,pos_] :=
   	Array[ ( M[[##2]] = L[[Sequence @@ #]] )&
           	[ {##}, Sequence @@ ({##}+pos-1) ] &,
               	Dimensions[L]
	]

Here is a faster variant for Version 2.2 that uses MapIndexed  
instead of Array and a much more direct and faster one using Version  
3.0.
(see also Paul Abbott, Tricks of the Trade,The Mathematica Journal  
Vol 6 Issue 4, Fall 1996, p20

SetAttributes[setsub2,HoldFirst]
setsub2[M_,L_,pos_] :=
	MapIndexed[(M[[##2]] = #1)&[#1,Sequence@@(#2+pos-1)]&, 	
		L,
		{Length[pos]}
	]
	
With Version 3.0

SetAttributes[setsub3,HoldFirst]
setsub3[M_,L_,pos_] := (M[[##]]=L)&@@ Range[pos,pos+ Dimensions[L]-1]



TIMINGS and CHECKS (all with Version 3.0)
set:= (M = Array[m,{5,5}]; L = Array[l,{3,3}];{p,q}={2,2};)

set
Do[setsub[M,L,{p,q}],{200}]//Timing//First
(M1=M);
	2.35 Second

set
Do[setsub2[M,L,{p,q}],{200}]//Timing//First
M1==M
	1.65 Second
	True

set
Do[setsub3[M,L,{p,q}],{200}]//Timing//First
M1==M
	0.366667 Second
	True

Allan Hayes
hay at haystack.demon.co.uk
http://www.haystack.demon.co.uk


  • Prev by Date: Mathematica 3.0 for Macintosh
  • Next by Date: Re: Interactive plotting in Mathematica?
  • Previous by thread: Mathematica 3.0 for Macintosh
  • Next by thread: Re: Interactive plotting in Mathematica?