MathGroup Archive 2011

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

Search the Archive

Re: Trying to use ReplacePart

  • To: mathgroup at smc.vnet.net
  • Subject: [mg120022] Re: Trying to use ReplacePart
  • From: Ray Koopman <koopman at sfu.ca>
  • Date: Wed, 6 Jul 2011 05:39:44 -0400 (EDT)
  • References: <201107010040.UAA24254@smc.vnet.net> <iup8eo$kt0$1@smc.vnet.net>

On Jul 3, 1:15 am, Iv=E1n Lazaro <gamins... at gmail.com> wrote:
> Thanks for the help; both solutions are much simpler than mine!
>
> However, is there some way to tell ReplacePart to "remember" each
> change it makes?

ReplacePart makes the changes one at a time.  replaceElements makes
them simultaneously and will be much faster for large matrices with
many elements to be replaced.

replaceElements[matrix_, positionlist_, valuelist_] :=
  Block[{cols = Length@matrix[[1]], vec = Flatten@matrix},
    vec[[ positionlist.{cols,1} - cols ]] = valuelist;
    Partition[vec,cols] ]

{rows, cols, n} = {4, 6, 9}
matrix = ConstantArray[0, {rows, cols}];
positions = Transpose@{
  RandomInteger[{1,rows}, n],
  RandomInteger[{1,cols}, n]}
values = RandomInteger[{10,99}, n]

{4,6,9}
{{1,5},{2,3},{1,6},{1,2},{2,6},{2,5},{3,2},{2,3},{1,6}}
{42,37,82,42,37,14,20,10,63}

matrix1 = ReplacePart[matrix, Thread[positions -> values]]
matrix2 = replaceElements[matrix, positions, values]
matrix2 === matrix1

{{0,42,0,0,42,63},{0,0,10,0,14,37},{0,20,0,0,0,0},{0,0,0,0,0,0}}
{{0,42,0,0,42,63},{0,0,10,0,14,37},{0,20,0,0,0,0},{0,0,0,0,0,0}}
True


  • Prev by Date: Re: How to write a "proper" math document
  • Next by Date: Re: Bug in Sum?
  • Previous by thread: Re: Trying to use ReplacePart
  • Next by thread: Re: Remote presentation clicker for mathematica slideshows.