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