Re: Another AppendTo replacement problem
- To: mathgroup at smc.vnet.net
- Subject: [mg118224] Re: Another AppendTo replacement problem
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Sun, 17 Apr 2011 07:52:25 -0400 (EDT)
On 4/16/11 at 7:36 AM, gaminster at gmail.com (Iv=C3=A1n Lazaro) wrote:
>I made a mistake in the code. Now it's fine. Sorry.
>NumBasis = 10000;
>q = matrA = ma = Table[0, {i, 2}];
>M = RandomComplex[{-1 - I, 1 + I}, {NumBasis, 2, 2}];
>M = Map[Orthogonalize, M];
>matr = RandomComplex[{-1 - I, 1 + I}, {2, 2}]
>Results = {};
>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,
>AppendTo[
>Results, {M[[Nbase]], Total[Eigenvalues[matrA[[k]]]]}]];
>}, {Nbase, 1, NumBasis}, {k, 1, 2}];
>M = Sort[Results, #1[[2]] < #2[[2]] &][[1, 1]];
Here is one way to avoid AppendTo
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,
Results = {Results, {M[[Nbase]],
Total[Eigenvalues[matrA[[k]]]]}}];}, {Nbase, 1,
NumBasis}, {k,
1, 2}];
M = SortBy[Partition[Flatten@Results, 2], Last][[1, 1]];
Here, I am saving the results as a nested list. Since you know
each loop adds a two element list, the desired array can be
created by partitioning the flattened nested list easily. The
end result will be the same but execute much faster.