title: Multiply a 3d tensor with a 2d matrix using torch.matmul
body: <p>I have two tensors in PyTorch, <code>z</code> is a 3d tensor of shape <code>(n_samples, n_features, n_views)</code> in which <code>n_samples</code> is the number of samples in the dataset, <code>n_features</code> is the number of features for each sample, and <code>n_views</code> is the number of different views that describe the same <code>(n_samples, n_features)</code> feature matrix, but with other values.</p>
  <p>I have another 2d tensor <code>b</code>, of shape <code>(n_samples, n_views)</code>, which purpose is to rescale all the features of the samples across the different views. In other words, it encapsulates the importance of the features of each view for the same sample.
  For example:</p>
  <pre class="lang-py prettyprint-override"><code>import torch
  z = torch.Tensor(([[2,3], [1,1], [4,5]], 
                    [[2,2], [1,2], [7,7]], 
                    [[2,3], [1,1], [4,5]], 
                    [[2,3], [1,1], [4,5]]))
  
  b = torch.Tensor(([1, 0], 
                    [0, 1], 
                    [0.2, 0.8], 
                    [0.5, 0.5]))
  print(z.shape, b.shape)
  
  &gt;&gt;&gt;torch.Size([4, 3, 2]) torch.Size([4, 2])
  </code></pre>
  <p>I want to obtain a third tensor <code>r</code> of shape <code>(n_samples, n_features)</code> as a result of operations between <code>z</code> and <code>b</code>.
  One possible solution is:</p>
  <pre class="lang-py prettyprint-override"><code>b = b.unsqueeze(1)
  r = z * b
  r = torch.sum(r, dim=-1)
  print(r, r.shape)
  &gt;&gt;&gt;tensor([[2.0000, 1.0000, 4.0000],
          [2.0000, 2.0000, 7.0000],
          [2.8000, 1.0000, 4.8000],
          [2.5000, 1.0000, 4.5000]]) torch.Size([4, 3])
  </code></pre>
  <p>Is it possible to achieve that same result using <code>torch.matmul()</code>?. I've tried many times to permute the dimensions of the two vector, but to no avail.</p>