matrixGenerator.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #!/usr/bin/python
  2. # This script generates matrices to solve a set of equations with n variables and n unknowns.
  3. # For each iteration, an n x n matrix and a 1 x n vector are created to describe the set of
  4. # equations in the form:
  5. #
  6. # a0x + b0y + c0z + d0w = e0
  7. # a1x + b1y + c1z + d1w = e1
  8. # a2x + b2y + c2z + d2w = e2
  9. # a3x + b3y + c3z + d3w = e3
  10. #
  11. # where in this case n=4.
  12. #
  13. # The files that are produced contain the dimension in line one, followed by
  14. # the n x n coefficient matrix, the 1 x n vector, and the 1 x n solution.
  15. # Each output file has the name matrixN.txt, where N is the value of n (e.g., matrix4.txt)
  16. #
  17. # The n x n matrix values and solution vector are confined to the values -0.9 to 0.9
  18. # (one decimal place), but the 1 x n vector can have two decimal place values.
  19. #
  20. # usage:
  21. # ./matrixGenerator a b c
  22. #
  23. # where a is the start value for n, b is the end value for n, and c is the step
  24. #
  25. # For example:
  26. #
  27. # ./matrixGenerator 16 256 4
  28. #
  29. # produces matrix16.txt, matrix20.txt, ... , matrix252.txt, matrix256.txt
  30. #
  31. # If there are no arguments, a is assumed to be 4 and only matrix4.txt is produced
  32. # If only a is present, only that matrix is produced
  33. # If a and b are present but not c, a step value of 1 is assumed
  34. import random
  35. import sys
  36. a = 4
  37. b = 4
  38. c = 1
  39. # parse command line
  40. try:
  41. a = int(sys.argv[1])
  42. b = a+1
  43. b = int(sys.argv[2])+1
  44. c = int(sys.argv[3])
  45. except IndexError:
  46. pass
  47. except ValueError:
  48. pass
  49. for sqSize in range(a,b,c):
  50. #size = 100
  51. #size = sqSize*sqSize
  52. size = sqSize;
  53. print size
  54. solnVec = []
  55. matrix = []
  56. bVector = []
  57. filename = "matrix"+str(size)+".txt"
  58. #f = open("matrix100.txt",'w')
  59. f = open(filename,'w')
  60. f.write(str(size)+"\n\n")
  61. for i in range(size):
  62. #solnVec.append(random.randint(-size,size)/float(size))
  63. solnVec.append(random.randint(-10,10)/float(10))
  64. for i in range(size):
  65. matrixRow = []
  66. for j in range(size):
  67. #matrixRow.append(random.randint(-size,size)/float(size))
  68. matrixRow.append(random.randint(-10,10)/float(10))
  69. matrix.append(matrixRow)
  70. for i in matrix:
  71. linResult = 0
  72. for j in range(size):
  73. f.write(str(i[j])+"\t")
  74. linResult+=i[j]*solnVec[j]
  75. bVector.append(linResult)
  76. f.write("\n")
  77. f.write("\n")
  78. for i in bVector:
  79. f.write(str(i)+"\t")
  80. f.write("\n\n");
  81. for i in solnVec:
  82. f.write(str(i)+"\t")
  83. f.write("\n\n")
  84. f.close()