tmatrix.nim 1016 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. discard """
  2. file: "tmatrix.nim"
  3. output: "111"
  4. """
  5. # Test overloading of [] with multiple indices
  6. type
  7. TMatrix* = object
  8. data: seq[float]
  9. fWidth, fHeight: int
  10. template `|`(x, y: int): untyped = y * m.fWidth + x
  11. proc createMatrix*(width, height: int): TMatrix =
  12. result.fWidth = width
  13. result.fHeight = height
  14. newSeq(result.data, width*height)
  15. proc width*(m: TMatrix): int {.inline.} = return m.fWidth
  16. proc height*(m: TMatrix): int {.inline.} = return m.fHeight
  17. proc `[]`*(m: TMatrix, x, y: int): float {.inline.} =
  18. result = m.data[x|y]
  19. proc `[]=`*(m: var TMatrix, x, y: int, val: float) {.inline.} =
  20. m.data[x|y] = val
  21. proc `-|`*(m: TMatrix): TMatrix =
  22. ## transposes a matrix
  23. result = createMatrix(m.height, m.width)
  24. for x in 0..m.width-1:
  25. for y in 0..m.height-1: result[y,x] = m[x,y]
  26. #m.row(0, 2) # select row
  27. #m.col(0, 89) # select column
  28. const
  29. w = 3
  30. h = 20
  31. var m = createMatrix(w, h)
  32. for i in 0..w-1:
  33. m[i, i] = 1.0
  34. for i in 0..w-1:
  35. stdout.write(m[i,i]) #OUT 111