Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #3502

Re: Trying to use ReplacePart

From Ray Koopman <koopman@sfu.ca>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Trying to use ReplacePart
Date 2011-07-06 09:36 +0000
Organization Steven M. Christensen and Associates, Inc and MathTensor, Inc.
Message-ID <iv1aa3$sjp$1@smc.vnet.net> (permalink)
References <201107010040.UAA24254@smc.vnet.net> <iup8eo$kt0$1@smc.vnet.net>

Show all headers | View raw


On Jul 3, 1:15 am, Iv=E1n Lazaro <gamins...@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

Back to comp.soft-sys.math.mathematica | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Re: Trying to use ReplacePart Iván Lazaro <gaminster@gmail.com> - 2011-07-03 08:15 +0000
  Re: Trying to use ReplacePart Ray Koopman <koopman@sfu.ca> - 2011-07-06 09:36 +0000

csiph-web