001// Copyright (c) FIRST and other WPILib contributors. 002// Open Source Software; you can modify and/or share it under the terms of 003// the WPILib BSD license file in the root directory of this project. 004 005package edu.wpi.first.math; 006 007import java.util.Objects; 008import org.ejml.simple.SimpleMatrix; 009 010/** 011 * A class for constructing arbitrary RxC matrices. 012 * 013 * @param <R> The number of rows of the desired matrix. 014 * @param <C> The number of columns of the desired matrix. 015 */ 016public class MatBuilder<R extends Num, C extends Num> { 017 /** 018 * Fills the matrix with the given data, encoded in row major form. (The matrix is filled row by 019 * row, left to right with the given data). 020 * 021 * @param rows The number of rows of the matrix. 022 * @param cols The number of columns of the matrix. 023 * @param data The data to fill the matrix with. 024 * @param <R> The number of rows of the matrix. 025 * @param <C> The number of columns of the matrix. 026 * @return The constructed matrix. 027 */ 028 public static final <R extends Num, C extends Num> Matrix<R, C> fill( 029 Nat<R> rows, Nat<C> cols, double... data) { 030 if (Objects.requireNonNull(data).length != rows.getNum() * cols.getNum()) { 031 throw new IllegalArgumentException( 032 "Invalid matrix data provided. Wanted " 033 + rows.getNum() 034 + " x " 035 + cols.getNum() 036 + " matrix, but got " 037 + data.length 038 + " elements"); 039 } 040 return new Matrix<>(new SimpleMatrix(rows.getNum(), cols.getNum(), true, data)); 041 } 042 043 protected final Nat<R> m_rows; 044 protected final Nat<C> m_cols; 045 046 /** 047 * Creates a new {@link MatBuilder} with the given dimensions. 048 * 049 * @param rows The number of rows of the matrix. 050 * @param cols The number of columns of the matrix. 051 * @deprecated Use {@link MatBuilder#fill} instead. 052 */ 053 @Deprecated(since = "2024", forRemoval = true) 054 public MatBuilder(Nat<R> rows, Nat<C> cols) { 055 this.m_rows = Objects.requireNonNull(rows); 056 this.m_cols = Objects.requireNonNull(cols); 057 } 058 059 /** 060 * Fills the matrix with the given data, encoded in row major form. (The matrix is filled row by 061 * row, left to right with the given data). 062 * 063 * @param data The data to fill the matrix with. 064 * @return The constructed matrix. 065 */ 066 public final Matrix<R, C> fill(double... data) { 067 return fill(m_rows, m_cols, data); 068 } 069}