Advertisement
RA2lover

Triangular linear equation set solver

Sep 23rd, 2014
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.30 KB | None | 0 0
  1. --task? create an algorithm capaple of solving triangular linear equation sets.
  2. --arguments are n(size of the matrix), matrix(the matrix containing the values) and results(the results of each line of the matrix)
  3.  
  4. --for example, the linear equation set{x+y+z=-1, y+z=2,z=3} would be represented as 3,{{1,1,1},{0,1,1},{0,0,1}},{1,2,3} and the solution {-1,-1,3}
  5.  
  6. function solve(n,matrix,results)
  7. --n is pretty much redundant and can be replaced with #matrix, but the assignment nazis still require it
  8. --you can probably uncomment this and maybe remove n from arguments.
  9. --n=#matrix
  10.  
  11.     local vars={}
  12. --initializing vars
  13.     for i=1,n do
  14.         vars[i]=0
  15.     end
  16.  
  17. --get
  18.     if matrix[#matrix][1]==0 then
  19.     --normal triangular matrix
  20.         for i=1,n do
  21.         --removing through substitution already known values
  22.             for j=1,n do
  23.             results[i]=(results[i]-(vars[j]*matrix[i][j]))
  24.             end
  25.         vars[i]=(results[i]/matrix[i][j])
  26.         end
  27.     else
  28.     --inverted triangular matrix
  29.         for i=n,1,-1 do
  30.         --i could do this by passing different args for the for loop, but i'm too lazy for that atm
  31.             for j=1,n do
  32.             results[i]=(results[i]-(vars[j]*matrix[i][j]))
  33.             end
  34.         vars[i]=(results[i]/matrix[i][j])
  35.         end
  36.        
  37.     end
  38.  
  39. return vars
  40. end
  41.  
  42.  
  43. --example test case
  44.  
  45. local a,b,c=3,{{1,1,1},{0,1,1},{0,0,1}},{1,2,3}
  46.  
  47. print(unpack(solve(a,b,c)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement