You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Builder.php 1.6 KiB

4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. *
  4. * Class for the creating "special" Matrices
  5. *
  6. * @copyright Copyright (c) 2018 Mark Baker (https://github.com/MarkBaker/PHPMatrix)
  7. * @license https://opensource.org/licenses/MIT MIT
  8. */
  9. namespace Matrix;
  10. /**
  11. * Matrix Builder class.
  12. *
  13. * @package Matrix
  14. */
  15. class Builder
  16. {
  17. /**
  18. * Create a new matrix of specified dimensions, and filled with a specified value
  19. * If the column argument isn't provided, then a square matrix will be created
  20. *
  21. * @param mixed $value
  22. * @param int $rows
  23. * @param int|null $columns
  24. * @return Matrix
  25. * @throws Exception
  26. */
  27. public static function createFilledMatrix($value, $rows, $columns = null)
  28. {
  29. if ($columns === null) {
  30. $columns = $rows;
  31. }
  32. $rows = Matrix::validateRow($rows);
  33. $columns = Matrix::validateColumn($columns);
  34. return new Matrix(
  35. array_fill(
  36. 0,
  37. $rows,
  38. array_fill(
  39. 0,
  40. $columns,
  41. $value
  42. )
  43. )
  44. );
  45. }
  46. /**
  47. * Create a new identity matrix of specified dimensions
  48. * This will always be a square matrix, with the number of rows and columns matching the provided dimension
  49. *
  50. * @param int $dimensions
  51. * @return Matrix
  52. * @throws Exception
  53. */
  54. public static function createIdentityMatrix($dimensions)
  55. {
  56. $grid = static::createFilledMatrix(null, $dimensions)->toArray();
  57. for ($x = 0; $x < $dimensions; ++$x) {
  58. $grid[$x][$x] = 1;
  59. }
  60. return new Matrix($grid);
  61. }
  62. }