I need to implement a multiplication formula where an row matrix of size 'n' is to be multiplied by an n*n matrix..
I have used DenseMatrix class to create the n*n matrix from a 2D array...but my problem is how to create a row Vector...
I can use the CompRowMatrix class to create a row matrix...but for that, input must be of 'Matrix'..but Matrix is an interface..can't instantiate it..the first constructor of CompRowMatrix class states it requires a 'non-zero array of indices' as input..but i am unable to understand what is this non-zero array of indices??
also, I can create a vector with DenseVector or any other suitable class..but there seems to be no method to directly multiply a vector with a matrix..
plz help
The
CompRowMatrix
class is not really intended to be used as a row vector, rather it is used to represent sparse matricies in such a way that it is easy to iterate over the matrix elements row by row.While it is possible to use
CompRowMatrix
as a vector by setting all rows other than the 1st to zero, this is more complicated for you as a programmer and less efficient for the code which has to assume that other rows could potentially become non-zero.Instead, use a
DenseVector
object to hold your row vector and use the mult method from theMatrix
interface. It accepts twoVector
objects as arguments and produces a vector-matrix product. The method is called on the matrix object being multiplied with the following arguments:x
, is the vector you want to multiply with your matrixy
, holds the result of the multiplicationSo to produce the vector-matrix product
y = x*A
(where bothx
andy
are1
xn
row vectors andA
is ann
xn
matrix), you would do something like this:Now you can use
y
in the rest of your code as needed. It is important that you allocatey
before the multiplication, but it is irrelevant what data it holds. Themult
method will overwrite whatever is iny
on exit.Also note that the ways I chose to initialize
x
andA
were not the only ways available. For instance, the above code automatically deep copies the arraysvecValues
andmatValues
when constructing the correspondingVector
andMatrix
objects. If you don't intend to use the arrays for any other purpose, then you should probably not perform this deep copy. You do this by passing an extra boolean paramter set to false in the constructor, e.g.You should refer to the javadoc both you and I linked to earlier for more constructor options. Be aware, however, that said javadoc is for a different version that the current release of MTJ (version 1.01 as of the time of this post). I don't know which version it is for nor have I been able to find javadoc for the current version, but I did spot a few differences between it and the current source code.