Subtraction.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Matrix\Operators;
  3. use Matrix\Matrix;
  4. use Matrix\Exception;
  5. class Subtraction extends Operator
  6. {
  7. /**
  8. * Execute the subtraction
  9. *
  10. * @param mixed $value The matrix or numeric value to subtract from the current base value
  11. * @throws Exception If the provided argument is not appropriate for the operation
  12. * @return $this The operation object, allowing multiple subtractions to be chained
  13. **/
  14. public function execute($value)
  15. {
  16. if (is_array($value)) {
  17. $value = new Matrix($value);
  18. }
  19. if (is_object($value) && ($value instanceof Matrix)) {
  20. return $this->subtractMatrix($value);
  21. } elseif (is_numeric($value)) {
  22. return $this->subtractScalar($value);
  23. }
  24. throw new Exception('Invalid argument for subtraction');
  25. }
  26. /**
  27. * Execute the subtraction for a scalar
  28. *
  29. * @param mixed $value The numeric value to subtracted from the current base value
  30. * @return $this The operation object, allowing multiple additions to be chained
  31. **/
  32. protected function subtractScalar($value)
  33. {
  34. for ($row = 0; $row < $this->rows; ++$row) {
  35. for ($column = 0; $column < $this->columns; ++$column) {
  36. $this->matrix[$row][$column] -= $value;
  37. }
  38. }
  39. return $this;
  40. }
  41. /**
  42. * Execute the subtraction for a matrix
  43. *
  44. * @param Matrix $value The numeric value to subtract from the current base value
  45. * @return $this The operation object, allowing multiple subtractions to be chained
  46. * @throws Exception If the provided argument is not appropriate for the operation
  47. **/
  48. protected function subtractMatrix(Matrix $value)
  49. {
  50. $this->validateMatchingDimensions($value);
  51. for ($row = 0; $row < $this->rows; ++$row) {
  52. for ($column = 0; $column < $this->columns; ++$column) {
  53. $this->matrix[$row][$column] -= $value->getValue($row + 1, $column + 1);
  54. }
  55. }
  56. return $this;
  57. }
  58. }