How to multiply a matrix by a vector in PyTorch
I'm playing around with PyTorch with the aim of learning it, and I have a very dumb question: how can I multiply a matrix by a single vector?

Here's what I've tried:

&gt;&gt;&gt; import torch
&gt;&gt;&gt; a = torch.rand(4,4)
&gt;&gt;&gt; a

 0.3162  0.4434  0.9318  0.8752
 0.0129  0.8609  0.6402  0.2396
 0.5720  0.7262  0.7443  0.0425
 0.4561  0.1725  0.4390  0.8770
[torch.FloatTensor of size 4x4]

&gt;&gt;&gt; b = torch.rand(4)
&gt;&gt;&gt; b

 0.1813
 0.7090
 0.0329
 0.7591
[torch.FloatTensor of size 4]

&gt;&gt;&gt; a.mm(b)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
RuntimeError: invalid argument 2: dimension 1 out of range of 1D tensor at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensor.c:24
&gt;&gt;&gt; a.mm(b.t())
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
RuntimeError: t() expects a 2D tensor, but self is 1D
&gt;&gt;&gt; b.mm(a)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
RuntimeError: matrices expected, got 1D, 2D tensors at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensorMath.c:1288
&gt;&gt;&gt; b.t().mm(a)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
RuntimeError: t() expects a 2D tensor, but self is 1D


On the other hand, if I do

&gt;&gt;&gt; b = torch.rand(4,2)


then my first attempt, a.mm(b), works fine. So the problem is just that I'm multiplying a vector rather than a matrix --- but how can I do this?

You're looking for 

torch.mv(a,b)


Note that for the future, you may also find torch.matmul() useful. torch.matmul() infers the dimensionality of your arguments and accordingly performs either dot products between vectors, matrix-vector or vector-matrix multiplication, matrix multiplication or batch matrix multiplication for higher order tensors. 
