       Re: Efficient Replacement Rules to Matrix?

• To: mathgroup at smc.vnet.net
• Subject: [mg21779] Re: [mg21743] Efficient Replacement Rules to Matrix?
• From: "Tomas Garza" <tgarza at mail.internet.com.mx>
• Date: Thu, 27 Jan 2000 22:57:01 -0500 (EST)
• Sender: owner-wri-mathgroup at wolfram.com

```Roger Jones [rmj at leland.stanford.edu] wrote:

> What is the most efficient (in terms of time) method to transform a set
> of replacement rules to a matrix.  For example, I have:
>
> matrix = ZeroMatrix;
> repmat = {{1, 1} -> 4., {5, 5} -> 3,{4, 4} -> 10,{2, 2} -> 2 + I 6, {3,
> 3} -> 40.};
>
> and I transfor to a matrix thus:
>
> matrix = ReplacePart[matrix, Sequence @@ #]) & /@ (
>       {Last[#], #[]} & /@ matrix);
>
> But for large matrices this is quite slow!  Is there a more efficient
> method?

Perhaps there are a couple of misprints in the expression for matrix above?
I guess (correct me if I'm wrong) it should read

matrix = (ReplacePart[matrix, Sequence @@ #]) & /@ (
{Last[#], #[]} & /@ repmat);

Notice the left parenthesis before ReplacePart, and repmat instead of matrix
at the end of the expression. If so, I think the problem is - partly - that
you end up with a huge matrix of dimensions {5, 5, 5}. From this, one has to
select those elements which really correspond to the desired matrix. I would
suggest a slightly different approach:

In:=
f[m_, j_] := ReplacePart[m, Sequence[repmat[[j, 2]]], repmat[[j, 1]]]

In:=
matrix = Fold[f, matrix, {1, 2, 3, 4, 5}]
Out=
{{4., 0, 0, 0, 0}, {0, 2 + 6 I, 0, 0, 0}, {0, 0, 40., 0, 0}, {0,
0, 0, 10, 0}, {0, 0, 0, 0, 3}}

No doubt this is much faster (I was too lazy to perform actual numeric
experiments with larger matrices), since it always remains within the {5, 5}
dimensions of the original matrix.

Tomas Garza
Mexico City

```

• Prev by Date: Re: Could this be improved?
• Next by Date: Re: Simplifying Finite Sums With A Variable # of Terms
• Previous by thread: Re: Efficient Replacement Rules to Matrix?
• Next by thread: Could this be improved?