# How to calculate the norm over a 2d matrix?

I have a distance matrix D with 2 dimensions from which I want to calculate the norm (||D||). Is it possible to use torch.norm(D) still having the two dimensions (same shape like before calculation) after the calculation? I saw that it is possible to calculate either the norm over the rows or over the colomns.

Hi,

Which norm are you looking for here?
Depending on what you’re looking for, you’ll need to set both dim and p to the right values.

hi, first of all thanks for yout help. Can you pls tell me what p is?

You can check the doc for details on each argument: https://pytorch.org/docs/stable/generated/torch.norm.html?highlight=norm#torch.norm

But as you will see there. This function can do many types of norms so you first need to know which norm you want

so p is float in my case. and I want to do the .norm() operation over the float entries of a 2d matrix (E, C) in which every entry is represening a distance. The shape (E, C) of the resulting matrix should not change.

I am not sure to follow what you mean. The norm of a matrix is a single number. Which norm are you looking for here? Euclidean, frobenius, … ?

okay thank you! I was quite unsure about that. the matrix holds euclidean distances in each entry. so you mean that I can not have a matrix as a result. the result should be a scalar value?

If these are already euclidean distances, then you don’t need the norm function?
Which value of p do you use for the distance computation?

I’ve forgotten to mention, that I took th.cdist() for the distance computation between cluster centers and data points (image patches) which is Dx-ci^dct in the following formula: -1/2h^2 * ||Dx - ci^dct||² . So you mean that I do not need to calculate the norm here in the formula with th.norm(x) where x = Dx - ci^dct because I already have the eucledian distances?

cdist already computes the p-norm distance.
Distance and norms are very similar in simple spaces.

okay, thank you very much.