The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Inactive » comp.soft-sys.math.mathematica

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Trying to use ReplacePart
Replies: 3   Last Post: Jul 6, 2011 4:54 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Ray Koopman

Posts: 3,383
Registered: 12/7/04
Re: Trying to use ReplacePart
Posted: Jul 6, 2011 4:54 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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


Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.