Skip to content

Commit 5718350

Browse files
committed
Split multiply into scalar and matrix versions. Deprecate the old function.
1 parent e63a3f1 commit 5718350

File tree

1 file changed

+38
-18
lines changed

1 file changed

+38
-18
lines changed

src/Matrix.php

Lines changed: 38 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -370,38 +370,58 @@ public function map(callable $callback)
370370
* @param Matrix|int|float $value Matrix or scalar to multiply with this matrix
371371
* @return Matrix
372372
* @throws MatrixException
373+
* @deprecated
373374
*/
374375
public function multiply($value)
375376
{
376377
if ($value instanceof Matrix) {
377-
if ($this->columns != $value->rows) {
378-
throw new MatrixException('Cannot multiply matrices of these sizes.');
379-
}
378+
return $this->multiplyMatrix($value);
379+
}
380+
381+
return $this->multiplyScalar($value);
382+
}
380383

381-
$literal = [];
384+
/**
385+
* @param Matrix $value
386+
* @return Matrix
387+
* @throws MatrixException
388+
*/
389+
public function multiplyMatrix(Matrix $value)
390+
{
391+
if ($this->columnCount != $value->rowCount) {
392+
throw new MatrixException('Cannot multiply matrices of these sizes.');
393+
}
382394

383-
for ($i = 0; $i < $this->rows; $i++) {
384-
$row = [];
395+
$literal = [];
385396

386-
for ($j = 0; $j < $value->columns; $j++) {
387-
$sum = 0;
397+
for ($i = 0; $i < $this->rowCount; $i++) {
398+
$row = [];
388399

389-
for ($k = 0; $k < $this->columns; $k++) {
390-
$sum += $this->get($i, $k) * $value->get($k, $j);
391-
}
400+
for ($j = 0; $j < $value->columnCount; $j++) {
401+
$sum = 0;
392402

393-
$row[] = $sum;
403+
for ($k = 0; $k < $this->columnCount; $k++) {
404+
$sum += $this->get($i, $k) * $value->get($k, $j);
394405
}
395406

396-
$literal[] = $row;
407+
$row[] = $sum;
397408
}
398409

399-
return new static($literal);
400-
} else {
401-
return $this->map(function ($element) use ($value) {
402-
return $element * $value;
403-
});
410+
$literal[] = $row;
404411
}
412+
413+
return new static($literal);
414+
}
415+
416+
/**
417+
* @param float $value
418+
* @return Matrix
419+
*/
420+
public function multiplyScalar($value)
421+
{
422+
return $this->map(function ($element) use ($value) {
423+
return $element * $value;
424+
});
405425
}
406426

407427
/**

0 commit comments

Comments
 (0)