Guest User

Mathematica test code

a guest
Jul 28th, 2011
759
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. (* All of this is already defined before hand *)
  2. L = 1200;
  3. t = -1.0;
  4. w = -1.0;
  5. e = Table[-2 t Cos[(n \[Pi])/(L + 1.)], {n, 1, L}];
  6. f = Table[Sqrt[2/(L + 1.)] Sin[(n \[Pi])/(L + 1)], {n, 1, L}];
  7.  
  8. (* Naive do loop *)
  9. AbsoluteTiming[h = Table[0, {2 L}, {2 L}];]
  10. AbsoluteTiming[Do[h[[i, i]] = e[[i]], {i, 1, L}];]
  11. AbsoluteTiming[Do[h[[i, i]] = e[[i - L]], {i, L + 1, 2 L}];]
  12. AbsoluteTiming[
  13. Do[h[[i, j]] = w f[[i]] f[[j - L]], {i, 1, L}, {j, L + 1, 2 L}];]
  14. AbsoluteTiming[Do[h[[i, j]] = h[[j, i]], {i, 1, 2 L}, {j, 1, i}];]
  15.  
  16. (* A more idiomatic way using built in functions *)
  17. AbsoluteTiming[h1 = w ArrayPad[Outer[Times, f, f], {{0, L}, {L, 0}}];]
  18. AbsoluteTiming[h1 += Transpose[h1];]
  19. AbsoluteTiming[h1 += DiagonalMatrix[Join[e, e]];]
  20.  
  21. (* Compiled version of the do loop *)
  22. cf = Compile[{{L, _Integer}, {e, _Real, 1}, {f, _Real, 1}},
  23. Module[{h},
  24. h = Table[0.0, {2 L}, {2 L}];
  25. Do[h[[i, i]] = e[[i]], {i, 1, L}];
  26. Do[h[[i, i]] = e[[i - L]], {i, L + 1, 2 L}];
  27. Do[h[[i, j]] = -f[[i]] f[[j - L]], {i, 1, L}, {j, L + 1, 2 L}];
  28. Do[h[[i, j]] = h[[j, i]], {i, 1, 2 L}, {j, 1, i}];
  29. h], CompilationTarget -> "C", RuntimeOptions -> "Speed"];
  30.  
  31. AbsoluteTiming[h2 = cf[L, e, f];]
  32.  
  33. (* Sanity checks. This may take a long time, so you should probably \
  34. reduce L to something more sane *)
  35. MatrixPlot[Chop[h - h1]]
  36. MatrixPlot[Chop[h - h2]]
  37. MatrixPlot[h]
  38. MatrixPlot[h1]
  39. MatrixPlot[h2]
  40.  
  41. k = 3 L/2;
  42.  
  43. (* Naive version *)
  44. AbsoluteTiming[
  45. p = Table[If[i == j && j <= k, 1, 0], {i, 2 L}, {j, 2 L}];]
  46.  
  47. (* Create identity matrix, then pad it *)
  48. AbsoluteTiming[
  49. p2 = ArrayPad[IdentityMatrix[k], {{0, 2 L - k}, {0, 2 L - k}}];]
  50.  
  51. (* Use a sparse array representation *)
  52. AbsoluteTiming[p3 = SparseArray[{i_, i_} /; i <= k -> 1, {2 L, 2 L}];]
  53.  
  54. (* Sanity checks *)
  55. MatrixPlot[Chop[p - p2]]
  56. MatrixPlot[Chop[p - p3]]
  57. MatrixPlot[p]
  58. MatrixPlot[p2]
  59. MatrixPlot[p3]
Advertisement
Add Comment
Please, Sign In to add comment