Advertisement
Guest User

Untitled

a guest
Jul 30th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Class Matrix
  5. *
  6. * @author Edgar Asatryan <nstdio@gmail.com>
  7. */
  8. class Matrix
  9. {
  10. private $data;
  11. private $rows;
  12. private $cols;
  13.  
  14. public function __construct(array $data)
  15. {
  16. $this->data = $data;
  17. $this->rows = count($data);
  18. $this->cols = count($data[0]);
  19. }
  20.  
  21. public function mul(Matrix $matrix)
  22. {
  23. $data = $matrix->getData();
  24.  
  25. $result = [];
  26. for ($i = 0; $i < $this->rows; $i++) {
  27. for ($j = 0; $j < $this->cols; $j++) {
  28. $t = 0;
  29. for ($k = 0; $k < $this->rows; $k++) {
  30. $t += $this->data[$i][$k] * $data[$k][$j];
  31. }
  32. $result[$i][$j] = $t;
  33. }
  34. }
  35.  
  36. return $result;
  37. }
  38.  
  39. /**
  40. * @return array
  41. */
  42. public function getData()
  43. {
  44. return $this->data;
  45. }
  46.  
  47. public function add(Matrix $matrix)
  48. {
  49. $data = $matrix->getData();
  50. $result = [];
  51. for ($i = 0; $i < $this->rows; $i++) {
  52. for ($j = 0; $j < $this->cols; $j++) {
  53. $result[$i][$j] = $this->data[$i][$j] + $data[$i][$j];
  54. }
  55. }
  56.  
  57. return $result;
  58. }
  59.  
  60. public function sub(Matrix $matrix)
  61. {
  62. $data = $matrix->getData();
  63. $result = [];
  64. for ($i = 0; $i < $this->rows; $i++) {
  65. for ($j = 0; $j < $this->cols; $j++) {
  66. $result[$i][$j] = $this->data[$i][$j] - $data[$i][$j];
  67. }
  68. }
  69.  
  70. return $result;
  71. }
  72.  
  73. public function scalarMul($number)
  74. {
  75. $result = [];
  76. for ($i = 0; $i < $this->rows; $i++) {
  77. for ($j = 0; $j < $this->cols; $j++) {
  78. $result[$i][$j] = $this->data[$i][$j] * $number;
  79. }
  80. }
  81.  
  82. return new Matrix($result);
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement