Yes, this is only the simple solution in the case where numbers are small.
It has the advantage to be fast and only using tensor-wide operations.
I’m not sure how to do this efficiently though.
If you find an efficient algorithm that mostly uses matrices (from numpy or matlab) that does this, do link it here, I’m sure we can adapt it to pytorch.