Complicated vector multiplication without iterating through the vector
I'm trying to calculate a loss value in a variation of multiclass classification.
I have my y tensor (the values correspond to the classes):
y = torch.tensor([ 1,  0,  2])

My y_pred is a 3x3 matrix of probability distributions:
y_pred = torch.tensor([[0.4937, 0.2657, 0.2986],
        [0.2553, 0.3845, 0.4384],
        [0.2510, 0.3498, 0.2630]])

The complication is that I also have a distance matrix (each class has some distance to other classes):
d_mtx = torch.tensor([[0, 0.7256, 0.7433],
        [0.6281, 0, 0.1171],
        [0.7580, 0.2513, 0]])

The loss that I'm trying to calculate is:
loss = 0
for class_value in range(len(y)):
    dis = torch.dot(d_mtx[y[class_value]], y_pred[class_value])
    loss += dis

Is there a way to calculate it efficiently without the iteration?
Update 1:
Tried @Yahia Zakaria approach and it works if my y_pred has the same size as my d_mtx, but otherwise I get an error:
RuntimeError: The size of tensor a (3) must match the size of tensor b (4) at non-singleton dimension 0

For example:
y = torch.tensor([ 1,  0,  2, 1])
y_pred = torch.tensor([[0.4937, 0.2657, 0.2986],
        [0.2553, 0.3845, 0.4384],
        [0.2510, 0.3498, 0.2630],
        [0.2510, 0.3498, 0.2630]])

d_mtx = torch.tensor([[0, 0.7256, 0.7433],
        [0.6281, 0, 0.1171],
        [0.7580, 0.2513, 0]])


You could do it like that:
loss = (d_mtx[y] * y_pred).sum()

This solution assumes the y is of type torch.int64 which is valid for the example you have shown.
