I'm quite new to mathematica and am trying to figure out how to optimise my code as currently it takes a very long time to compile and makes it hard to bug test. The first part that creates the graph of the eigenvalues against k is relatively fast, but the second part takes a large chunk of time so i'm wondering what i should change about this. Any help/advice would be really appreciated.
t4 = 0.3
phi = Pi/2
haldzigzaghamiltonian[n_, k_, delta_] := Table[
If[Mod[u, 2] != 0 && v == (u + 1), -2*Cos[k/2],
If[Mod[u, 2] == 0 && v == (u - 1), -2*Cos[k/2],
If[Mod[u + v - 1, 4] == 0 && Abs[u - v] < 2, -1,
If[
Mod[u, 2] != 0 && (v == (u + 2) || v == (u - 2)), -t4*2*
Cos[phi + k/2],
If[
Mod[u, 2] == 0 && (v == (u + 2) || v == (u - 2)), -t4*2*
Cos[k/2 - phi],
If[Mod[u, 2] != 0 && u == v, -t4*2*Cos[phi + k] + delta,
If[Mod[u, 2] == 0 && u == v, -t4*2*Cos[k + phi] - delta,
0]]]]]]],
{u, 2*n}, {v, 2*n}];
vx[n_, k_] := Table[If[u == v, -t4*Sin[k + phi],
If[(u + v > 3) && (Abs[u - v] == 2), -t4*Sin[k/2 - phi],
If[(Mod[v, 2] == 0) && Abs[u - v] == 1, -Sin[k/2], 0]]],
{u, 2*n}, {v, 2*n}];
oka[n_] :=
Table[If[Mod[u, 2] != 0 && v == u, 1, 0], {v, 2*n}, {u, 2*n}];
okb[n_] :=
Table[If[Mod[u, 2] == 0 && v == u, 1, 0], {v, 2*n}, {u, 2*n}];
nvalue = 3;
k = Range[0, 2*Pi, 2*Pi/99];
delta = 0.3;
eigvals =
Table[N[
Re[Eigenvalues[
haldzigzaghamiltonian[nvalue, k[[i]], delta]]]], {i, 100}] ;
ListPlot[
Table[{k[[i]], eigvals[[i]][[j]]}, {i, 0, 100}, {j, 0, 2*nvalue}]]
nvalue = 20;
kvalue = 7*Pi/9;
del = Table[
eigvecsk =
Eigenvectors[{haldzigzaghamiltonian[nvalue, k[[i]], delta]}];
eigvalsk =
Eigenvalues[haldzigzaghamiltonian[nvalue, k[[i]], delta]];
f[n_] := If[eigvalsk[[n]] <= 0, 1, 0];
e[n_, nmax_, k_] := eigvalsk[[n]];
onm[n_, m_, nmax_] := eigvecsk[[n]]\[Conjugate] . eigvecsk[[m]];
vxnm[n_, m_, nmax_, k_] :=
eigvecsk[[n]]\[Conjugate] . vx[nmax, k] . eigvecsk[[m]];
func[n_, m_, nmax_,
k_] := (f[n] - f[m])/(e[n, nmax, k] - e[m, nmax, k])^2*
onm[n, m, nmax]*vxnm[m, n, nmax, k];
N[Re[Sum[
If[p != q, func[p, q, nvalue, k[[i]]], 0], {p, 1, 2*nvalue}, {q,
1, 2*nvalue}]]], {i, 100}];
ListLinePlot[Table[{k[[b]], del[[b]]}, {b, 0, 100}],
PlotRange -> Full]