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  @SuppressWarnings("LineLength")
028  public final Matrix<R, C> fill(double... data) {
029    if (Objects.requireNonNull(data).length != this.m_rows.getNum() * this.m_cols.getNum()) {
030      throw new IllegalArgumentException(
031          "Invalid matrix data provided. Wanted "
032              + this.m_rows.getNum()
033              + " x "
034              + this.m_cols.getNum()
035              + " matrix, but got "
036              + data.length
037              + " elements");
038    } else {
039      return new Matrix<>(new SimpleMatrix(this.m_rows.getNum(), this.m_cols.getNum(), true, data));
040    }
041  }
042
043  /**
044   * Creates a new {@link MatBuilder} with the given dimensions.
045   *
046   * @param rows The number of rows of the matrix.
047   * @param cols The number of columns of the matrix.
048   */
049  public MatBuilder(Nat<R> rows, Nat<C> cols) {
050    this.m_rows = Objects.requireNonNull(rows);
051    this.m_cols = Objects.requireNonNull(cols);
052  }
053}