# Generalized scalar product for matrices

Let $$X$$ and $$Y$$ be matrices of a dimension $$m \times n$$. I would like to keep $$m$$ and $$n$$ as a variable and define a scalar function $$\operatorname{scalar}: X , Y \to \mathbb R$$ $$\operatorname{scalar}(X,Y ) = \sqrt{\sum_{j=1}^n \sum_{i=1}^m (x_{ij} - y_{ij})^2}$$

This is how I orginally implemented it:

skalar[{{a_,b_},{c_,d_},{e_,f_}},{{g_,h_},{i_,j_},{k_,l_}}] =
Sqrt[(a-g)^2 +(b-h)^2 +(c-i)^2 +(d-j)^2 +(e-k)^2 +(f-l)^2];

As you can see, it is bad.

• Norm[Array[A, {4, 3}] - Array[B, {4, 3}], "Frobenius"] Aug 31, 2023 at 14:08

1. The elementwise difference of 2 matrices x,y can simply be written as: x-y.

2. The elementwise square of a matrix x is simply x^2

3. To add all elements of a matrix, you may use "Flatten" and "Total"

scalar[x_, y_] := Sqrt[Total[Flatten[(x - y)^2]]]

With this, e.g.:

x = {{1, 2}, {1, 2}};
y = {{2, 3}, {2, 3}};
scalar[x, y]

2

Another method perhaps closer to the textbook could be: (Excuse the code formatting, it is deliberate)

Clear["Global`*"]
scalar[x_?MatrixQ, y_?MatrixQ] := Module[
{m = First@Dimensions@x
, n = Last@Dimensions@x
},
Sqrt[\!$$\*UnderoverscriptBox[\(\[Sum]$$, $$j = 1$$, $$n$$]$$\*UnderoverscriptBox[\(\[Sum]$$, $$i = 1$$, $$m$$]
\*SuperscriptBox[$$(x[\([$$$$i, j$$$$]$$] -
y[$$[$$$$i, j$$$$]$$])\), $$2$$]\)\)]
]

Screenshot:

Usage:

m = 2;
n = 3;
X = Array[x, {m, n}];
Y = Array[y, {m, n}];
scalar[X, Y]

$$\sqrt{(x(1,1)-y(1,1))^2+(x(1,2)-y(1,2))^2+(x(1,3)-y(1,3))^2+(x(2,1)-y(2,1))^2+(x(2,2)-y(2,2))^2+(x(2,3)-y(2,3))^2}$$

or

SeedRandom[1];
g = RandomReal[{-5, 5}, {4, 2}];
h = RandomReal[{-5, 5}, {4, 2}];
scalar[g, h]

13.3447