/** * <p> * Performs the following operation:<br> * <br> * B = A + αI * <p> * * @param A A square matrix. Not modified. * @param B A square matrix that the results are saved to. Modified. * @param alpha Scaling factor for the identity matrix. */ public static void addIdentity(FMatrix1Row A, FMatrix1Row B, float alpha) { if (A.numCols != A.numRows) { throw new ArgumentException("A must be square"); } if (B.numCols != A.numCols || B.numRows != A.numRows) { throw new ArgumentException("B must be the same shape as A"); } int n = A.numCols; int index = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++, index++) { if (i == j) { B.set(index, A.get(index) + alpha); } else { B.set(index, A.get(index)); } } } }
/** * <p> * Extracts a row or column vector from matrix A. The first element in the matrix is at element (rowA,colA). * The next 'length' elements are extracted along a row or column. The results are put into vector 'v' * start at its element v0. * </p> * * @param A Matrix that the vector is being extracted from. Not modified. * @param rowA Row of the first element that is extracted. * @param colA Column of the first element that is extracted. * @param length Length of the extracted vector. * @param row If true a row vector is extracted, otherwise a column vector is extracted. * @param offsetV First element in 'v' where the results are extracted to. * @param v Vector where the results are written to. Modified. */ public static void subvector(FMatrix1Row A, int rowA, int colA, int length, bool row, int offsetV, FMatrix1Row v) { if (row) { for (int i = 0; i < length; i++) { v.set(offsetV + i, A.get(rowA, colA + i)); } } else { for (int i = 0; i < length; i++) { v.set(offsetV + i, A.get(rowA + i, colA)); } } }
public static void setSubMatrix(FMatrix1Row src, FMatrix1Row dst, int srcRow, int srcCol, int dstRow, int dstCol, int numSubRows, int numSubCols) { for (int i = 0; i < numSubRows; i++) { for (int j = 0; j < numSubCols; j++) { float val = src.get(i + srcRow, j + srcCol); dst.set(i + dstRow, j + dstCol, val); } } }
/** * <p> * Sets A ∈ ℜ <sup>m × n</sup> equal to an outer product multiplication of the two * vectors. This is also known as a rank-1 operation.<br> * <br> * A = x * y' * where x ∈ ℜ <sup>m</sup> and y ∈ ℜ <sup>n</sup> are vectors. * </p> * <p> * Which is equivalent to: A<sub>ij</sub> = x<sub>i</sub>*y<sub>j</sub> * </p> * * <p> * These functions are often used inside of highly optimized code and therefor sanity checks are * kept to a minimum. It is not recommended that any of these functions be used directly. * </p> * * @param x A vector with m elements. Not modified. * @param y A vector with n elements. Not modified. * @param A A Matrix with m by n elements. Modified. */ public static void outerProd(FMatrixD1 x, FMatrixD1 y, FMatrix1Row A) { int m = A.numRows; int n = A.numCols; int index = 0; for (int i = 0; i < m; i++) { float xdat = x.get(i); for (int j = 0; j < n; j++) { A.set(index++, xdat * y.get(j)); } } }