How can I multiply a matrix by a vector using JAMA?

11,061

Solution 1

Here is simple example of wanted operation:

double[][] array = {{1.,2.,3},{1.,2.,3.},{1.,2.,3.}}; 
Matrix a = new Matrix(array);   
Matrix b = new Matrix(new double[]{1., 1., 1.}, 1);     
Matrix c = b.times(a);  
System.out.println(Arrays.deepToString(c.getArray()));

Result:

[[3.0, 6.0, 9.0]]

In other words that is:

enter image description here

Solution 2

Why can't you use Matrix's arrayTimes method? A vector is just a 1 x n matrix (I think) so can't you initialize a second matrix with just 1 dimension and use arrayTimes?

Matrix a = new Matrix( [[1,2,3],[1,2,3],[1,2,3]] );
Matrix b = new Matrix( [[1,2,3]] ); // this is a vector
Matrix c = a.arrayTimes(b.transpose); // transpose so that the inner dimensions agree

This is what I think would work from reading the doc.

Share:
11,061

Related videos on Youtube

skaffman
Author by

skaffman

Updated on June 01, 2022

Comments

  • skaffman
    skaffman almost 2 years

    I'm trying to create a vector from an array of doubles. I then want to multiply this vector by a matrix. Does anyone know how I can achieve this? Below is a really simple example that I would like to get working.

    // Create the matrix (using JAMA)
    Matrix a = new Matrix( [[1,2,3],[1,2,3],[1,2,3]] );
    
    // Create a vector out of an array
    ...
    
    // Multiply the vector by the matrix
    ...
    
  • Grzegorz Szpetkowski
    Grzegorz Szpetkowski almost 13 years
    @Jon: Note that Matrix class API (math.nist.gov/javanumerics/jama/doc/Jama/Matrix.html) is your friend to get more options :)
  • Joehot200
    Joehot200 over 9 years
    Hi! Sorry to be an idiot, but could you please give us an example of what happens when [1 1 1] is something like [2 5 3] instead?
  • Grzegorz Szpetkowski
    Grzegorz Szpetkowski over 9 years
    @Joehot200: Matrix multiplication is fairly easy to learn by yourself, this should make your clear how to do it. Essentially you multiply "rows by columns", each product is then summed up and placed accordingly.
  • Joehot200
    Joehot200 over 9 years
    Right. Got it. Thanks. I can't believe that I had got all the way to learning sines, cosines, tangent, vector multiplication, etc, and yet never encountered matrix-vector multiplication.