I write a function which is a matrix as below:
mat[kx_, n_] := (
Clear[a, b, h];
h = Table[0, {i, 1, 2 n}, {j, 1, 2 n}];
a[m_] := 2 m - 1;
b[m_] := 2 m;
t1 = 1;
aa = 1;
Do[
h[[b[i], a[i]]] =
t1 (E^(I kx ((Sqrt[3] aa)/2)) + E^(-I kx ((Sqrt[3] aa)/2)));
h[[a[i], b[i]]] =
t1 (E^(I kx ((Sqrt[3] aa)/2)) + E^(-I kx ((Sqrt[3] aa)/2)));
If[i + 1 <= n, h[[b[i + 1], a[i]]] = t1, Null];
If[i - 1 > 0, h[[a[i - 1], b[i]]] = t1, Null];
, {i, 1, n}];
h)
I test the speed of the matrix construction
In[90]:= Table[mat[kx, 7], {kx, 0., 1., 1/3000}]; // AbsoluteTiming
Out[90]= {1.971113, Null}
the dimension of the mat[kx,7] is 14, so I test the following randomreal matrix
In[91]:= Table[
RandomReal[{0, 1}, {14, 14}], {kx, 0., 1.,
1/3000}]; // AbsoluteTiming
Out[91]= {0.027002, Null}
it is 100 times faster.
So I wonder if my mat function could be 100 times faster.
I know my programming is poor, but I don't know how to code it elegent and efficient.So can somebody help me with it and point it out which is the most important factor that make my mat function so slow?
mat2[kx_, n_] := ( h = Table[0, {i, 1, 2 n}, {j, 1, 2 n}]; a[m_] = 2 m - 1; b[m_] = 2 m; t1 = 1; aa = 1; e = (E^(I kx ((Sqrt[3] aa)/2)) + E^(-I kx ((Sqrt[3] aa)/2))) // FullSimplify; Do[h[[b[i], a[i]]] = t1 e; h[[a[i], b[i]]] = t1 e; If[i + 1 <= n, h[[b[i + 1], a[i]]] = t1, Null]; If[i - 1 > 0, h[[a[i - 1], b[i]]] = t1, Null];, {i, 1, n}]; h). – b.gates.you.know.what Aug 25 '13 at 08:18Ifs and you can always tryCompile. – b.gates.you.know.what Aug 25 '13 at 09:01Compile. But I got a littel problem usingCompile. Can you take a look at the message I drop to Mr.Wizard? – matheorem Aug 25 '13 at 12:23