Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401]

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