MATLAB: How to generate random invertible symmetric positive semidefinite square matrix using MATLAB

MATLAB

matrixSize = 10
A = random.rand(matrixSize,matrixSize)
B = numpy.dot(A,A.transpose())
I am not sure, this generates random positive semi-define matrix B. But I want to generate random invertible symmetric positive semidefinite square matrix. Thank for your help.

Best Answer

matrixSize = 10;
while true
A = rand(matrixSize, MatrixSize);
if rank(A) == matrixSize; break; end %will be true nearly all the time
end
B = A' * A;
According to https://en.wikipedia.org/wiki/Positive-definite_matrix, for any square matrix A, A' * A is positive semi-definite, and rank(A' * A) is equal to rank(A) . Matrices are invertible if they have full rank. So all we have to do is generate an initial random matrix with full rank and we can then easily find a positive semi-definite matrix derived from it. Nearly all random matrices are full rank, so the loop I show will almost always only iterate once and is very very unlikely to need more than a very small number of iterations.