Re: Another AppendTo replacement problem
- To: mathgroup at smc.vnet.net
- Subject: [mg118221] Re: Another AppendTo replacement problem
- From: "Sjoerd C. de Vries" <sjoerd.c.devries at gmail.com>
- Date: Sun, 17 Apr 2011 07:51:52 -0400 (EDT)
- References: <iobv13$bfp$1@smc.vnet.net>
The usual trick is to replace AppendTo[list,elem] with list {list,elem}. The list is going to look like {{{{{{elem1},elem2},elem3},elem4},elem5},elem6} At the end you do a list = Flatten[list] and all is fine; In this case your elements have a structure which has to be protected against Flatten. That can be done by replacing the list that contains them with a dummy head (fl) like this: Results= {Results, fl[M[[Nbase]], Total[Eigenvalues[matrA[[k]]]]]} Right after the loop you Flatten and get rid of the head fl: Results2 = Flatten[Results] /. fl -> List; For NumBasis =10000 this version is twice as fast, but for NumBasis =100,000 the speedup is already a factor of 20! Cheers -- Sjoerd Turn to StackOverflow for faster answers to Mathematica questions http://stackoverflow.com/questions/tagged/mathematica On Apr 16, 1:37 pm, Iv=E1n Lazaro <gamins... at gmail.com> 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]]; > > Thanks in advance!