I am implementing basic machine learning algorithm in Ruby, 1.9.3.
I try to use class Matrix and Vector for the arithmetics. But when I try to multiply a vector by another vector, it says "ExceptionForMatrix::ErrOperationNotDefined: Operation(*) can't be defined: Vector op Vector".
But the doc of Ruby, 1.9,3 says:
*(x) Multiplies the vector by x, where x is a number or another vector.
My code and output is here:
> a = Vector[1,2,3]
=> Vector[1, 2, 3]
> b = Vector[1,2,3]
=> Vector[1, 2, 3]
> a * b
ExceptionForMatrix::ErrOperationNotDefined: Operation(*) can't be defined: Vector op Vector
To define multiplication between a matrix A and a vector x (i.e., the matrix-vector product), we need to view the vector as a column matrix. We define the matrix-vector product only for the case when the number of columns in A equals the number of rows in x.
Dot product – also known as the "scalar product", a binary operation that takes two vectors and returns a scalar quantity. The dot product of two vectors can be defined as the product of the magnitudes of the two vectors and the cosine of the angle between the two vectors.
Assuming that each operation for an field F can be done in O(1) time, this implies that the worst-case complexity of matrix-vector multiplication is Θ(mn).
Although the documentation clearly states that you can multiply a vector by another vector, it's nonsensical, and, as zisasign points out, the implementation doesn't permit it.
However, you can turn either vector into a one-row matrix using the covector
method, which you can then multiply to give a meaningful calculation:
a = Vector[1, 2, 3]
b = Vector[10, 100, 1000]
a.covector * b
# => Vector[3210]
a * b.covector
# => Matrix[[10, 100, 1000], [20, 200, 2000], [30, 300, 3000]]
The documentation is wrong. When you look at the code linked in the doc, there is
def *(x)
case x
when Numeric
els = @elements.collect{|e| e * x}
Vector.elements(els, false)
when Matrix
Matrix.column_vector(self) * x
when Vector
Vector.Raise ErrOperationNotDefined, "*", self.class, x.class
else
apply_through_coercion(x, __method__)
end
end
Multiplying (as in matrix-multiplication) a (column-)vector by a (column-)vector does not make sense, anyway. Maybe you want inner_product
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With