user843337
user843337

Reputation:

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

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
...

Upvotes: 5

Views: 11348

Answers (3)

Ziggy
Ziggy

Reputation: 22365

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.

Upvotes: 1

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37914

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

Upvotes: 13

Ishtar
Ishtar

Reputation: 11662

How about this:

double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
Matrix A = new Matrix(vals);

From http://math.nist.gov/javanumerics/jama/doc/Jama/Matrix.html

Upvotes: 0

Related Questions