# Defining a sum on the elements of a matrix

I am interested in defining the quantity $$H=n-1-\sum_{i\ne j} R_{ij},$$where $$R$$ is a random $$n\times n$$ Hermitian matrix (as a side question: how should I go about adding the condition $$\rm{Tr}(R)=1$$?). I start with

a[n_Integer] = Table[RandomComplex[], {n}, {n}]
R = (1/2) (a + ConjugateTranspose[a])
MatrixForm[R]


to generate the matrix, but the line

H[n_Integer] := n - 1 - Sum[R[[i,j]] Boole[i!=j], {i,1,n}, {j,1,n}]


isn't working at all. As a complete beginner I'm having trouble with spotting any mistake. What goes wrong?

• You can get the total of all elements and then remove the diagonal. Feb 21, 2020 at 15:57
• Yes, that also makes sense, but H[n_Integer]:=n-1-Sum[R[i,j],{i,1,n},{j,1,n}]-Tr[R] also doesn't work for me. Is there a function to sum all the elements directly? Feb 21, 2020 at 16:04
• Look at Total to sum the elements. Feb 21, 2020 at 16:08
• Total[R] only sums along the columns, though... Feb 21, 2020 at 16:12
• Then either apply Total twice or use the optional second argument to choose the level at which to sum: Total[R, 2] Feb 21, 2020 at 16:13

ClearAll[symmetrize, mR, h]
symmetrize = (1/2) (# + ConjugateTranspose @ #) &;

mR[n_Integer] := Module[{a = symmetrize@RandomComplex[1 + I, {n, n}]}, a/Tr[a]]

h[m_] := Length[m] - 1 - Total[MapIndexed[Drop]@m, 2]


Examples:

SeedRandom[1]

r = mR @ 3;

TeXForm @ MatrixForm[r]


$$\left( \begin{array}{ccc} 0.561874\, +0. i & 0.102843\, -0.0725292 i & 0.45773\, -0.0262951 i \\ 0.102843\, +0.0725292 i & 0.165912\, +0. i & 0.102042\, +0.0178369 i \\ 0.45773\, +0.0262951 i & 0.102042\, -0.0178369 i & 0.272215\, +0. i \\ \end{array} \right)$$

Tr @ r


1.+ 0. I

Abs[Tr @ r]


1.

h @ r


0.674769 + 6.93889*10^-18 I

SeedRandom[1]

h[mR[3]]


0.674769 + 6.93889*10^-18 I

Update: "my ultimate goal is to plot a function of h f[h[m]] as a function of n."_

ClearAll[hmR]
hmR[n_] := h@mR[n]

SeedRandom[1]
hmR[3]


0.674769 + 6.93889*10^-18 I

flist = {Re, Im, Total[ReIm[#]] &};

Row[Table[DiscretePlot[f[hmR[n]], {n, 2, 10}, Frame -> True,
ImageSize -> 1 -> 20, PlotLabel -> f],
{f, flist}],
Spacer[10]]


• @kgrl, thanks for the answer. I can't say I understand everything you've written, but it works fine. However, I still have an issue: my ultimate goal is to plot a function of $h$ f[h[m_]] as a function of $n$. It is not immediately clear to me how to make the code you wrote work to do this... Feb 22, 2020 at 11:56
• @TotalNoob, please see the update.
– kglr
Feb 22, 2020 at 20:14
• thanks again for your help. I have actually asked another question to deal with the plot, at this link. I'll look into your code right away and see what I can understand. Feb 22, 2020 at 20:25