MathGroup Archive 2011

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

Search the Archive

Re: Trying to use ReplacePart

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


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


  • 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.