Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

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


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

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




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

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.