Creating a random symmetric matrix with a particular rank

The documentation about LinearAlgebra has a section on Constructing Matrices, but the examples of random matrices using RandomReal don't offer an obvios way to impose symmetry or rank.

There is a similar question (77441) asking for a matrix with a particular rank, but doesn't address the symmetry constraint.

Is there any way to create a $$n \times n$$ random symmetric matrix with a specified MatrixRank $$r$$?

i.e. A $$6 \times 6$$ random symmetric matrix with rank $$3$$.

• @rhermans gave a wonderful answer, but it cannot hurt to have a second way of doing it: I suggest this symm[n_] := Module[{mm = RandomReal[10, {n, n}]}, (mm + Transpose[mm])/2] which creates a symmetric random matrix. Then I remembered the strongly related to the OP answer which constructs a random matrix of specific rank. Combining the above should do the trick, but I am stupid and I have not managed that yet
– bmf
Feb 2 at 12:09
• And to expand a bit, using the above pieces of information the naive RandomMatrix[rank_, m_] := Sum[TensorProduct@symm[m], {i, rank}] fails and likewise for RandomMatrix[rank_, m_] := Sum[TensorProduct /@ symm[m], {i, rank}] as the rank becomes 6 instead of 3
– bmf
Feb 2 at 12:10
• @lotus2019 I tried to improve your question to show the minimum diligence one could expect: a search on the documentation and a search on the site (with links) and an explanation why neither was enough to answer your particular problem. Also improved the formatting, the tags and made explicit the need to check for MatrixRank. Next time you should do that or more, not less. Feb 2 at 12:41
• @rhermans Thank you for your excellent answer. I have searched this website before ask this question, and found the answer to create a random matrix with a specific rank, and the answer to create a random symmetric matrix, but it has little to do with this question. I also considered creating a random symmetric matrix first, and then reducing the rank of the random symmetric matrix by replacing some rows and columns, but this method is not elegant. Next time, I will put these efforts into the question for reference. Thank you for your kindly advice and editing. Feb 2 at 14:23

Documentation

There is a ResourceFunction calledRandomMatrix contributed by Dennis M Schneider.

For matrices of kind "Idempotent","Symmetric", "SymmetricIdempotent" or "Hermitian", setting the option "Rank" → k will choose a matrix of that kind having rank $$k$$.

Matrix

m = ResourceFunction["RandomMatrix"][
"Symmetric"
, Real
, {-1,1}
, {6,6}
, "Rank"->3
]


Tests

Rule[ #, #[m] ]& /@ {
MatrixQ,
SquareMatrixQ,
Dimensions,
MatrixRank,
SymmetricMatrixQ,
DiagonalizableMatrixQ,
HermitianMatrixQ,
NormalMatrixQ,
PositiveSemidefiniteMatrixQ
} // TableForm


• This is very slick!
– bmf
Feb 2 at 12:03