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 edu.wpi.first.math.numbers.N1;
008import org.ejml.simple.SimpleMatrix;
009
010/**
011 * A shape-safe wrapper over Efficient Java Matrix Library (EJML) matrices.
012 *
013 * <p>This class is intended to be used alongside the state space library.
014 *
015 * @param <R> The number of rows in this matrix.
016 */
017public class Vector<R extends Num> extends Matrix<R, N1> {
018  /**
019   * Constructs an empty zero vector of the given dimensions.
020   *
021   * @param rows The number of rows of the vector.
022   */
023  public Vector(Nat<R> rows) {
024    super(rows, Nat.N1());
025  }
026
027  /**
028   * Constructs a new {@link Vector} with the given storage. Caller should make sure that the
029   * provided generic bounds match the shape of the provided {@link Vector}.
030   *
031   * <p>NOTE:It is not recommended to use this constructor unless the {@link SimpleMatrix} API is
032   * absolutely necessary due to the desired function not being accessible through the {@link
033   * Vector} wrapper.
034   *
035   * @param storage The {@link SimpleMatrix} to back this vector.
036   */
037  public Vector(SimpleMatrix storage) {
038    super(storage);
039  }
040
041  /**
042   * Constructs a new vector with the storage of the supplied matrix.
043   *
044   * @param other The {@link Vector} to copy the storage of.
045   */
046  public Vector(Matrix<R, N1> other) {
047    super(other);
048  }
049
050  @Override
051  public Vector<R> times(double value) {
052    return new Vector<>(this.m_storage.scale(value));
053  }
054
055  @Override
056  public Vector<R> div(int value) {
057    return new Vector<>(this.m_storage.divide(value));
058  }
059
060  @Override
061  public Vector<R> div(double value) {
062    return new Vector<>(this.m_storage.divide(value));
063  }
064
065  /**
066   * Returns the dot product of this vector with another.
067   *
068   * @param other The other vector.
069   * @return The dot product.
070   */
071  public double dot(Vector<R> other) {
072    double dot = 0.0;
073
074    for (int i = 0; i < getNumRows(); ++i) {
075      dot += get(i, 0) * other.get(i, 0);
076    }
077
078    return dot;
079  }
080
081  /**
082   * Returns the norm of this vector.
083   *
084   * @return The norm.
085   */
086  public double norm() {
087    double squaredNorm = 0.0;
088
089    for (int i = 0; i < getNumRows(); ++i) {
090      squaredNorm += get(i, 0) * get(i, 0);
091    }
092
093    return Math.sqrt(squaredNorm);
094  }
095}