Search All of the Math Forum:

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

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

 Messages: [ Previous | Next ]
 Ray Koopman Posts: 3,383 Registered: 12/7/04
Re: Trying to use ReplacePart
Posted: Jul 6, 2011 4:54 AM

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

Date Subject Author
7/3/11 Iván Lazaro
7/6/11 Ray Koopman
7/5/11 Dana DeLouis