Multiplication.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Matrix\Operators;
  3. use Matrix\Matrix;
  4. use \Matrix\Builder;
  5. use Matrix\Exception;
  6. use Throwable;
  7. class Multiplication extends Operator
  8. {
  9. /**
  10. * Execute the multiplication
  11. *
  12. * @param mixed $value The matrix or numeric value to multiply the current base value by
  13. * @throws Exception If the provided argument is not appropriate for the operation
  14. * @return $this The operation object, allowing multiple multiplications to be chained
  15. **/
  16. public function execute($value, string $type = 'multiplication'): Operator
  17. {
  18. if (is_array($value)) {
  19. $value = new Matrix($value);
  20. }
  21. if (is_object($value) && ($value instanceof Matrix)) {
  22. return $this->multiplyMatrix($value, $type);
  23. } elseif (is_numeric($value)) {
  24. return $this->multiplyScalar($value, $type);
  25. }
  26. throw new Exception("Invalid argument for $type");
  27. }
  28. /**
  29. * Execute the multiplication for a scalar
  30. *
  31. * @param mixed $value The numeric value to multiply with the current base value
  32. * @return $this The operation object, allowing multiple mutiplications to be chained
  33. **/
  34. protected function multiplyScalar($value, string $type = 'multiplication'): Operator
  35. {
  36. try {
  37. for ($row = 0; $row < $this->rows; ++$row) {
  38. for ($column = 0; $column < $this->columns; ++$column) {
  39. $this->matrix[$row][$column] *= $value;
  40. }
  41. }
  42. } catch (Throwable $e) {
  43. throw new Exception("Invalid argument for $type");
  44. }
  45. return $this;
  46. }
  47. /**
  48. * Execute the multiplication for a matrix
  49. *
  50. * @param Matrix $value The numeric value to multiply with the current base value
  51. * @return $this The operation object, allowing multiple mutiplications to be chained
  52. * @throws Exception If the provided argument is not appropriate for the operation
  53. **/
  54. protected function multiplyMatrix(Matrix $value, string $type = 'multiplication'): Operator
  55. {
  56. $this->validateReflectingDimensions($value);
  57. $newRows = $this->rows;
  58. $newColumns = $value->columns;
  59. $matrix = Builder::createFilledMatrix(0, $newRows, $newColumns)
  60. ->toArray();
  61. try {
  62. for ($row = 0; $row < $newRows; ++$row) {
  63. for ($column = 0; $column < $newColumns; ++$column) {
  64. $columnData = $value->getColumns($column + 1)->toArray();
  65. foreach ($this->matrix[$row] as $key => $valueData) {
  66. $matrix[$row][$column] += $valueData * $columnData[$key][0];
  67. }
  68. }
  69. }
  70. } catch (Throwable $e) {
  71. throw new Exception("Invalid argument for $type");
  72. }
  73. $this->matrix = $matrix;
  74. return $this;
  75. }
  76. }