Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby 1.9.3, a vector can't be multiplied by another vector?

Tags:

ruby

vector

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
like image 243
zisasign Avatar asked May 16 '13 10:05

zisasign


People also ask

Can you multiply a matrix by a 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.

What is a vector times a vector?

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.

What is the complexity of multiplying a matrix with a vector?

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


2 Answers

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]]
like image 194
threedaymonk Avatar answered Oct 11 '22 07:10

threedaymonk


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?

like image 36
undur_gongor Avatar answered Oct 11 '22 09:10

undur_gongor