Copy the matrix to another matrix.

@param Matrix $matrix
184911
protected function copy(Matrix $matrix) {
        for ($i=0; $i<static::ROWS; $i++) {
            for ($j=0; $j<static::COLUMNS; $j++) {
                $this->vectors[$i][$j] = $matrix[$i][$j];
            }
        }
    }
1240852
public static void byRow(Matrix m) {
        for (int i = 0; i < m.rows(); ++i) {
            double rowSum = 0;
            for (int j = 0; j < m.columns(); ++j)
                rowSum += m.get(i,j);

            // Skip row whose sume is zero.
            if (rowSum == 0) 
                continue;
            for (int j = 0; j < m.columns(); ++j)
                m.set(i,j, m.get(i,j) / rowSum);
        }
    }
1131033
public function solve(Matrix $B)
    {
        if ($B->getRows() != $this->m) {
            throw MatrixException::notSquareMatrix();
        }

        if (!$this->isNonsingular()) {
            throw MatrixException::singularMatrix();
        }

        // Copy right hand side with pivoting
        $nx = $B->getColumns();
        $X  = $this->getSubMatrix($B->toArray(), $this->piv, 0, $nx - 1);
        // Solve L*Y = B(piv,:)
        for ($k = 0; $k < $this->n; ++$k) {
            for ($i = $k + 1; $i < $this->n; ++$i) {
                for ($j = 0; $j < $nx; ++$j) {
                    $X[$i][$j] -= $X[$k][$j] * $this->LU[$i][$k];
                }
            }
        }
        // Solve U*X = Y;
        for ($k = $this->n - 1; $k >= 0; --$k) {
            for ($j = 0; $j < $nx; ++$j) {
                $X[$k][$j] /= $this->LU[$k][$k];
            }
            for ($i = 0; $i < $k; ++$i) {
                for ($j = 0; $j < $nx; ++$j) {
                    $X[$i][$j] -= $X[$k][$j] * $this->LU[$i][$k];
                }
            }
        }
        return $X;
    }
479104
protected function lessMatrix(Matrix $b) : self
    {
        if ($b->m() !== $this->m) {
            throw new DimensionalityMismatchException('Matrix A requires'
                . " $this->m rows but Matrix B has {$b->m()}.");
        }

        if ($b->n() !== $this->n) {
            throw new DimensionalityMismatchException('Matrix A requires'
                . " $this->n columns but Matrix B has {$b->n()}.");
        }

        $c = [];

        foreach ($this->a as $i => $rowA) {
            $rowB = $b[$i];
            $temp = [];

            foreach ($rowA as $j => $value) {
                $temp[] = $value < $rowB[$j] ? 1 : 0;
            }

            $c[] = $temp;
        }

        return self::quick($c);
    }
1310730
public void copyStructure( DMatrixSparseCSC orig ) {
        reshape(orig.numRows, orig.numCols, orig.nz_length);
        this.nz_length = orig.nz_length;
        System.arraycopy(orig.col_idx,0,col_idx,0,orig.numCols+1);
        System.arraycopy(orig.nz_rows,0,nz_rows,0,orig.nz_length);
    }
586594
protected function doTransform(Matrix $mA, $extra = null)
    {
        /** @noinspection PhpInternalEntityUsedInspection */
        $this->assertParameterIsMatrix($extra)
             ->assertMatrixColumnsAreEqual($mA, $extra)
             ->assertMatrixIsComplete($mA)
             ->assertMatrixIsComplete($extra);

        //previous checks have determined both matrices have same number of
        //columns - so we only need to check one for zero rows
        if ($mA->is('empty')) {
            return new Matrix(array());
        }

        $data = array_merge($mA->toArray(), $extra->toArray());

        return new Matrix($data);
    }
1275229
protected function multiplyMatrix(Matrix $b) : Matrix
    {
        if ($this->n !== $b->m()) {
            throw new DimensionalityMismatchException('Vector A requires'
                . " $this->n rows but Matrix B has {$b->m()}.");
        }

        $c = [];

        foreach ($b as $i => $row) {
            $valueA = $this->a[$i];

            $temp = [];

            foreach ($row as $valueB) {
                $temp[] = $valueA * $valueB;
            }

            $c[] = $temp;
        }

        return Matrix::quick($c);
    }
209090
public static void swapRows(Matrix matrix, long row1, long row2) {
		double temp = 0;
		long cols = matrix.getColumnCount();
		for (long col = 0; col < cols; col++) {
			temp = matrix.getAsDouble(row1, col);
			matrix.setAsDouble(matrix.getAsDouble(row2, col), row1, col);
			matrix.setAsDouble(temp, row2, col);
		}
	}
836687
public T copy() {
        T ret = createLike();
        ret.getMatrix().set(this.getMatrix());
        return ret;
    }
108742
public static function inverse(Matrix $matrix)
    {
        if (!$matrix->isSquare()) {
            throw new Exception('Inverse can only be calculated for a square matrix');
        }

        $determinant = self::getDeterminant($matrix);
        if ($determinant == 0.0) {
            throw new Exception('Inverse can only be calculated for a matrix with a non-zero determinant');
        }

        if ($matrix->rows == 1) {
            return new Matrix([[1 / $matrix->getValue(1, 1)]]);
        }

        return self::getAdjoint($matrix)
            ->multiply(1 / $determinant);
    }
796322
public static void matrixFill(Object[][] matrix, Object val) {
        if (matrix != null) {
            for (int i = 0, n = matrix.length; i < n; i++) {
                if (matrix[i] != null) {
                    for (int j = 0, m = matrix[i].length; j < m; j++) {
                        matrix[i][j] = val;
                    }
                }
            }
        }
    }
276256
public static Matrix copy(Matrix m) {
		if (m==null) throw new NullPointerException();
		Matrix copy=createMatrix(m.getRowCount(), m.getColumnCount());
		for (int row=0; row<m.getRowCount(); row++) for (int col=0; col<m.getColumnCount(); col++)
			copy.set(row, col, m.getQuick(row, col));
		return copy;
	}

	/**
	 * Creates a copy of a matrix.
	 * @param m the matrix to copy
	 * @return a new matrix with the same dimensions and contents as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Matrix2 copy(Matrix2 m) {
		return (Matrix2) copy((Matrix)m);
	}

	/**
	 * Creates a copy of a matrix.
	 * @param m the matrix to copy
	 * @return a new matrix with the same dimensions and contents as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Matrix3 copy(Matrix3 m) {
		return (Matrix3) copy((Matrix)m);
	}

	/**
	 * Creates a copy of a matrix.
	 * @param m the matrix to copy
	 * @return a new matrix with the same dimensions and contents as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Vector copy(Vector m) {
		return (Vector) copy((Matrix)m);
	}

	/**
	 * Creates a copy of a matrix.
	 * @param m the matrix to copy
	 * @return a new matrix with the same dimensions and contents as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Vector2 copy(Vector2 m) {
		return (Vector2) copy((Matrix)m);
	}

	/**
	 * Creates a copy of a matrix.
	 * @param m the matrix to copy
	 * @return a new matrix with the same dimensions and contents as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Vector3 copy(Vector3 m) {
		return (Vector3) copy((Matrix)m);
	}

	/**
	 * Creates a copy of a matrix.
	 * @param m the matrix to copy
	 * @return a new matrix with the same dimensions and contents as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Vector4 copy(Vector4 m) {
		return (Vector4) copy((Matrix)m);
	}
	
	/**
	 * Creates a matrix with the same dimensions as the argument.
	 * @param matrix the template matrix
	 * @return a new zero matrix with the same dimensions as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Matrix createLike(Matrix matrix) {
		return createMatrix(matrix.getRowCount(), matrix.getColumnCount());
	}
	
	/**
	 * Creates a matrix with the same dimensions as the argument.
	 * @param matrix the template matrix
	 * @return a new zero matrix with the same dimensions as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Matrix2 createLike(Matrix2 matrix) {
		return (Matrix2) createMatrix(matrix.getRowCount(), matrix.getColumnCount());
	}
	
	/**
	 * Creates a matrix with the same dimensions as the argument.
	 * @param matrix the template matrix
	 * @return a new zero matrix with the same dimensions as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Matrix3 createLike(Matrix3 matrix) {
		return (Matrix3) createMatrix(matrix.getRowCount(), matrix.getColumnCount());
	}
	
	/**
	 * Creates a matrix with the same dimensions as the argument.
	 * @param matrix the template matrix
	 * @return a new zero matrix with the same dimensions as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Vector createLike(Vector matrix) {
		return (Vector) createMatrix(matrix.getRowCount(), matrix.getColumnCount());
	}
	
	/**
	 * Creates a matrix with the same dimensions as the argument.
	 * @param matrix the template matrix
	 * @return a new zero matrix with the same dimensions as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Vector2 createLike(Vector2 matrix) {
		return (Vector2) createMatrix(matrix.getRowCount(), matrix.getColumnCount());
	}
	
	/**
	 * Creates a matrix with the same dimensions as the argument.
	 * @param matrix the template matrix
	 * @return a new zero matrix with the same dimensions as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Vector3 createLike(Vector3 matrix) {
		return (Vector3) createMatrix(matrix.getRowCount(), matrix.getColumnCount());
	}
	
	/**
	 * Creates a matrix with the same dimensions as the argument.
	 * @param matrix the template matrix
	 * @return a new zero matrix with the same dimensions as the argument
	 * @throws NullPointerException if {@code matrix} is {@code null}
	 */
	public static Vector4 createLike(Vector4 matrix) {
		return (Vector4) createMatrix(matrix.getRowCount(), matrix.getColumnCount());
	}
	
	/**
	 * Creates an identity matrix of the specified dimension.
	 * @param size the dimension of the matrix
	 * @return a <code>size</code>×<code>size</code> identity matrix
	 * @throws IllegalArgumentException if the size is not positive
	 */
	public static Matrix identity(int size) {
		Matrix m = MatrixFactory.createMatrix(size, size);
		for (int i = 0; i < size; i++)
			m.set(i, i, 1);
		return m;
	}

	/**
	 * Creates a matrix of the specified size whose elements are all 1.
	 * @param rows the number of rows
	 * @param columns the number of columns
	 * @return a <code>rows</code>×<code>columns</code> matrix whose elements are all 1
	 * @throws IllegalArgumentException if either argument is non-positive
	 */
	public static Matrix ones(int rows, int columns) {
		Matrix m = MatrixFactory.createMatrix(rows, columns);
		for (int i = 0; i < m.getRowCount(); i++)
			for (int j = 0; j < m.getColumnCount(); j++)
				m.set(i, j, 1);
		return m;
	}

	/**
	 * Creates a matrix of the specified size whose elements are pseudorandom, uniformly distributed
	 * values between 0 (inclusive) and 1 (exclusive).
	 * @param rows the number of rows
	 * @param columns the number of columns
	 * @return a <code>rows</code>×<code>columns</code> matrix of random elements
	 * @throws IllegalArgumentException if either argument is non-positive
	 */
	public static Matrix random(int rows, int columns) {
		Matrix m = MatrixFactory.createMatrix(rows, columns);
		for (int i = 0; i < m.getRowCount(); i++)
			for (int j = 0; j < m.getColumnCount(); j++)
				m.set(i, j, Math.random());
		return m;
	}
	
	//
	// Matrix creation from arrays
	//
	
	/**
	 * Creates a matrix and initializes its elements from an array. The parameter should be a {@code double[r][c]}
	 * array with {@code r>0} and {@code c>0}. The matrix element at row {@code row} and column {@code col} will be
	 * {@code elements[row][col]}.
	 * @param elements the array containing the elements of the matrix
	 * @return the new matrix initialized from the array
	 * @throws NullPointerException if the array is {@code null}
	 * @throws IllegalArgumentException if the dimensions of the array are not valid
	 */
	public static Matrix createMatrix(double[][] elements) {
		Matrix m=createMatrix(elements.length, elements[0].length);
		for (int row=0; row<m.getRowCount(); row++) {
			double[] rowData=elements[row];
			if (rowData.length!=m.getColumnCount()) throw new IllegalArgumentException("Invalid array");
			for (int col=0; col<m.getColumnCount(); col++) {
				m.set(row, col, rowData[col]);
			}
		}
		return m;
	}
	
	/**
	 * Creates a matrix and initializes its elements from an array. The parameter should be a {@code double[2][2]}
	 * array. The matrix element at row {@code row} and column {@code col} will be
	 * {@code elements[row][col]}.
	 * @param elements the array containing the elements of the matrix
	 * @return the new matrix initialized from the array
	 * @throws NullPointerException if the array is {@code null}
	 * @throws IllegalArgumentException if the dimensions of the array are not correct
	 */
	public static Matrix2 createMatrix2(double[][] elements) {
		Matrix m=createMatrix(elements);
		if (m.getRowCount()!=2 || m.getColumnCount()!=2)
			throw new IllegalArgumentException("Array describes a matrix of size "+m.getRowCount()+"x"+m.getColumnCount()+" instead of 2x2");
		return (Matrix2)m;
	}
	
	/**
	 * Creates a matrix and initializes its elements from an array. The parameter should be a {@code double[3][3]}
	 * array. The matrix element at row {@code row} and column {@code col} will be
	 * {@code elements[row][col]}.
	 * @param elements the array containing the elements of the matrix
	 * @return the new matrix initialized from the array
	 * @throws NullPointerException if the array is {@code null}
	 * @throws IllegalArgumentException if the dimensions of the array are not correct
	 */
	public static Matrix3 createMatrix3(double[][] elements) {
		Matrix m=createMatrix(elements);
		if (m.getRowCount()!=3 || m.getColumnCount()!=3)
			throw new IllegalArgumentException("Array describes a matrix of size "+m.getRowCount()+"x"+m.getColumnCount()+" instead of 3x3");
		return (Matrix3)m;
	}
	
	/**
	 * Creates a vector and initializes its elements from an array.
	 * @param elements the array containing the elements of the vector
	 * @return the new vector initialized from the array
	 * @throws NullPointerException if the array is {@code null}
	 * @throws IllegalArgumentException if the length of the array is zero
	 */
	public static Vector createVector(double[] elements) {
		Vector v=createVector(elements.length);
		for (int i=0; i<elements.length; i++)
			v.setCoordQuick(i, elements[i]);
		return v;
	}
	
	/**
	 * Creates a matrix backed by the specified data structure.
	 * @param core the data structure for the new matrix
	 * @return a matrix of proper type using the specified matrix core for its implementation
	 * @throws NullPointerException if {@code core} is {@code null}
	 */
	public static Matrix create(MatrixCore core) {
		if (core.getColumnCount()==1) {
			switch (core.getRowCount()) {
				case 2: return new CoredVector2Impl(core);
				case 3: return new CoredVector3Impl(core);
				case 4: return new CoredVector4Impl(core);
				default: return new CoredVectorImpl(core);
			}
		} else {
			if (core.getRowCount()==2 && core.getColumnCount()==2)
				return new CoredMatrix2Impl(core);
			if (core.getRowCount()==3 && core.getColumnCount()==3)
				return new CoredMatrix3Impl(core);
			return new CoredMatrixImpl(core);
		}
	}
}
1338131
public static function add(Matrix $matrix, Matrix $matrix2) : Matrix {
        $type  = get_class($matrix);
        $type2 = get_class($matrix2);

        if ($type !== $type2) {
            throw new InvalidArgumentException("Can only add matrices of same size.");
        }

        $result = new $type();

        for ($i=0;$i<$type::ROWS;$i++) {
            for ($j=0;$j<$type::COLUMNS;$j++) {
                $result[$i][$j] = $matrix[$i][$j] + $matrix2[$i][$j];
            }
        }

        return $result;
    }
956647
@Override
    public Matrix applyCommon(Matrix a, Matrix b) {
        int n = a.rows() * b.rows();
        int m = a.columns() * b.columns();
        int p = b.rows();
        int q = b.columns();

        Matrix result = a.blankOfShape(n, m);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                result.set(i, j, a.get(i / p, j / q) * b.get(i % p, j % q));
            }
        }

        return result;
    }
1176828
public static void setMatrix(final double[][] m1, final int r0, final int r1, final int[] c, final double[][] m2) {
    assert r0 <= r1 : ERR_INVALID_RANGE;
    assert r1 <= m1.length : ERR_MATRIX_DIMENSIONS;
    for(int i = r0; i < r1; i++) {
      final double[] row1 = m1[i], row2 = m2[i - r0];
      for(int j = 0; j < c.length; j++) {
        row1[c[j]] = row2[j];
      }
    }
  }
134286
public void setMatrix(int i0, int i1, int[] c, Matrix X)
    {
        try
        {
            for (int i = i0; i <= i1; i++)
            {
                for (int j = 0; j < c.length; j++)
                {
                    A[i][c[j]] = X.get(i - i0, j);
                }
            }
        }
        catch (ArrayIndexOutOfBoundsException e)
        {
            throw new ArrayIndexOutOfBoundsException("Submatrix indices");
        }
    }
106925
function set( $row, $col, $value )
    {
        if ( $value !== 0 )
        {
            $pos = $row * $this->Cols + $col;
            $pos = base_convert( $pos, 10, 36 );
            $this->Matrix["*$pos"] = $value;
        }
    }