Re: Another AppendTo replacement problem
- To: mathgroup at smc.vnet.net
- Subject: [mg118231] Re: Another AppendTo replacement problem
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Sun, 17 Apr 2011 07:53:40 -0400 (EDT)
- References: <iobuv2$bec$1@smc.vnet.net>
Hi, I've seen your other post but for me the code in the first worked while the code in the second gave me a lot of error message. Since I think the difference might not be relevant for the AppendTo-problem, I'm just using the code in the first post... > I've read multiple times in this forum about the slow performance of > AppendTo with big lists. I have now a problem with it, but have not > been able to replace it properly. This is a toy version of my problem. > The code below have to be run multiple times, but it is really slow. I > wonder if somebody have an idea about this AppendTo problem. You can use a well known trick to first build your list as something that performs like a linked list and than use Flatten to get the form you actually want. Since the entries in your list are lists, I'm using a different Head, but the rest can be found in many other posts: NumBasis = 10000; M = RandomComplex[{-1 - I, 1 + I}, {NumBasis, 2, 2}]; M = Map[Orthogonalize, M]; matr = RandomComplex[{-1 - I, 1 + I}, {2, 2}] Timing[ q = matrA = ma = Table[0, {i, 2}]; results2 = list[]; Do[ ma[[k]] = KroneckerProduct[M[[Nbase, k]], Conjugate[M[[Nbase, k]]]]; matrA[[k]] = Chop[matr.ma[[k]]]; matrA[[k]] = matrA[[k]]/Tr[matrA[[k]].matrA[[k]]] // Chop; If[k == 2, results2 = list[results2, {M[[Nbase]], Eigenvalues[matrA[[k]]], {k, 1, 2}}] ], {Nbase, 1, NumBasis}, {k, 1, 2} ]; results2 = List @@ Flatten[results2]; ] actually I think something like this would probably be somewhat easier to understand, but it seems to be slightly slower (but still a lot faster than the AppendTo-Version): Timing[ q = matrA = ma = Table[0, {i, 2}]; results3 = Flatten[Table[ ma[[k]] = KroneckerProduct[M[[Nbase, k]], Conjugate[M[[Nbase, k]]]]; matrA[[k]] = Chop[matr.ma[[k]]]; matrA[[k]] = matrA[[k]]/Tr[matrA[[k]].matrA[[k]]] // Chop; If[k == 2, {M[[Nbase]], Eigenvalues[matrA[[k]]], {k, 1, 2}}, Unevaluated[Sequence[]] ], {Nbase, 1, NumBasis}, {k, 1, 2} ], 1]; ] hth, albert