Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Class Matrix
- *
- * @author Edgar Asatryan <nstdio@gmail.com>
- */
- class Matrix
- {
- private $data;
- private $rows;
- private $cols;
- public function __construct(array $data)
- {
- $this->data = $data;
- $this->rows = count($data);
- $this->cols = count($data[0]);
- }
- public function mul(Matrix $matrix)
- {
- $data = $matrix->getData();
- $result = [];
- for ($i = 0; $i < $this->rows; $i++) {
- for ($j = 0; $j < $this->cols; $j++) {
- $t = 0;
- for ($k = 0; $k < $this->rows; $k++) {
- $t += $this->data[$i][$k] * $data[$k][$j];
- }
- $result[$i][$j] = $t;
- }
- }
- return $result;
- }
- /**
- * @return array
- */
- public function getData()
- {
- return $this->data;
- }
- public function add(Matrix $matrix)
- {
- $data = $matrix->getData();
- $result = [];
- for ($i = 0; $i < $this->rows; $i++) {
- for ($j = 0; $j < $this->cols; $j++) {
- $result[$i][$j] = $this->data[$i][$j] + $data[$i][$j];
- }
- }
- return $result;
- }
- public function sub(Matrix $matrix)
- {
- $data = $matrix->getData();
- $result = [];
- for ($i = 0; $i < $this->rows; $i++) {
- for ($j = 0; $j < $this->cols; $j++) {
- $result[$i][$j] = $this->data[$i][$j] - $data[$i][$j];
- }
- }
- return $result;
- }
- public function scalarMul($number)
- {
- $result = [];
- for ($i = 0; $i < $this->rows; $i++) {
- for ($j = 0; $j < $this->cols; $j++) {
- $result[$i][$j] = $this->data[$i][$j] * $number;
- }
- }
- return new Matrix($result);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement