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  final Nat<R> m_rows;
018  final Nat<C> m_cols;
019
020  /**
021   * Fills the matrix with the given data, encoded in row major form. (The matrix is filled row by
022   * row, left to right with the given data).
023   *
024   * @param data The data to fill the matrix with.
025   * @return The constructed matrix.
026   */
027  public final Matrix<R, C> fill(double... data) {
028    if (Objects.requireNonNull(data).length != this.m_rows.getNum() * this.m_cols.getNum()) {
029      throw new IllegalArgumentException(
030          "Invalid matrix data provided. Wanted "
031              + this.m_rows.getNum()
032              + " x "
033              + this.m_cols.getNum()
034              + " matrix, but got "
035              + data.length
036              + " elements");
037    } else {
038      return new Matrix<>(new SimpleMatrix(this.m_rows.getNum(), this.m_cols.getNum(), true, data));
039    }
040  }
041
042  /**
043   * Creates a new {@link MatBuilder} with the given dimensions.
044   *
045   * @param rows The number of rows of the matrix.
046   * @param cols The number of columns of the matrix.
047   */
048  public MatBuilder(Nat<R> rows, Nat<C> cols) {
049    this.m_rows = Objects.requireNonNull(rows);
050    this.m_cols = Objects.requireNonNull(cols);
051  }
052}