Operator.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Matrix\Operators;
  3. use Matrix\Matrix;
  4. use Matrix\Exception;
  5. abstract class Operator
  6. {
  7. /**
  8. * Stored internally as a 2-dimension array of values
  9. *
  10. * @property mixed[][] $matrix
  11. **/
  12. protected $matrix;
  13. /**
  14. * Number of rows in the matrix
  15. *
  16. * @property integer $rows
  17. **/
  18. protected $rows;
  19. /**
  20. * Number of columns in the matrix
  21. *
  22. * @property integer $columns
  23. **/
  24. protected $columns;
  25. /**
  26. * Create an new handler object for the operation
  27. *
  28. * @param Matrix $matrix The base Matrix object on which the operation will be performed
  29. */
  30. public function __construct(Matrix $matrix)
  31. {
  32. $this->rows = $matrix->rows;
  33. $this->columns = $matrix->columns;
  34. $this->matrix = $matrix->toArray();
  35. }
  36. /**
  37. * Compare the dimensions of the matrices being operated on to see if they are valid for addition/subtraction
  38. *
  39. * @param Matrix $matrix The second Matrix object on which the operation will be performed
  40. * @throws Exception
  41. */
  42. protected function validateMatchingDimensions(Matrix $matrix)
  43. {
  44. if (($this->rows != $matrix->rows) || ($this->columns != $matrix->columns)) {
  45. throw new Exception('Matrices have mismatched dimensions');
  46. }
  47. }
  48. /**
  49. * Compare the dimensions of the matrices being operated on to see if they are valid for multiplication/division
  50. *
  51. * @param Matrix $matrix The second Matrix object on which the operation will be performed
  52. * @throws Exception
  53. */
  54. protected function validateReflectingDimensions(Matrix $matrix)
  55. {
  56. if ($this->columns != $matrix->rows) {
  57. throw new Exception('Matrices have mismatched dimensions');
  58. }
  59. }
  60. /**
  61. * Return the result of the operation
  62. *
  63. * @return Matrix
  64. */
  65. public function result()
  66. {
  67. return new Matrix($this->matrix);
  68. }
  69. }