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  /** Number of rows. */
044  protected final Nat<R> m_rows;
045
046  /** Number of columns. */
047  protected final Nat<C> m_cols;
048
049  /**
050   * Creates a new {@link MatBuilder} with the given dimensions.
051   *
052   * @param rows The number of rows of the matrix.
053   * @param cols The number of columns of the matrix.
054   * @deprecated Use {@link MatBuilder#fill} instead.
055   */
056  @Deprecated(since = "2024", forRemoval = true)
057  public MatBuilder(Nat<R> rows, Nat<C> cols) {
058    this.m_rows = Objects.requireNonNull(rows);
059    this.m_cols = Objects.requireNonNull(cols);
060  }
061
062  /**
063   * Fills the matrix with the given data, encoded in row major form. (The matrix is filled row by
064   * row, left to right with the given data).
065   *
066   * @param data The data to fill the matrix with.
067   * @return The constructed matrix.
068   */
069  public final Matrix<R, C> fill(double... data) {
070    return fill(m_rows, m_cols, data);
071  }
072}