How to assign value of a multidimensional tensor by indexing a tensor?

I have a tensor tcls of shape (n_objects, n_classes) and a 1 dim tensor for classes targets[…, 5][obj]. I would like to set for each row “n” of tcls the “nth” element of targets[…, 5][obj].

tcls = torch.zeros_like(preds[..., 5:][obj], device=config.DEVICE)
new_tcls = "how can I do it?"
lcls = self.BCE_cls(preds[..., 5:][obj], new_tcls)  # BCE

Any suggestion?

I know I could do I with a naive for loop, but I am striving to learn it in a “linear algebra” way to enhance GPU computations

After searching all around stackoverflow and PyTorch forum I found the solution here: Fill value to matrix based on index - #5 by ptrblck

Here it’s how it should be, I have no clue why…

tcls = torch.zeros_like(preds[..., 5:][obj], device=config.DEVICE)
        tcls[torch.arange(tcls.size(0)), targets[..., 5][obj].long()] = targets[..., 5][obj].float()
        lcls = self.BCE_cls(preds[..., 5:][obj], tcls)  # BCE```