I am working on a project for a numerical methods class comparing two iterative methods for solving $Ax=b$, and I was wondering what type of functions Matlab has for generating arbitrarily large square matrices that could be used for testing purposes.

For example, is there any function that can generate diagonally dominant matrices easily? I could probably write one easily enough, but if there is one already that would be easier.

I'm looking for anything similar to magic(n) that will generate a matrix with some given property that I can look at. I have looked through the Matlab documentation but couldn't find a list of any kind.


I think that you're looking for the gallery function. It has over 60 types of test matrices. For the particular case of diagonally dominant matrices, you might look at the 'dorr' option:

A = full(gallery('dorr',5,0.01))

You can find the code for most of these matrix generation functions in the matlabroot/toolbox/matlab/elmat/private/ directory, where matlabroot is the root directory of your Matlab installation.

If you need random diagonally dominant matrices, then you might look at the answers to this StackOverflow question. I believe that this is equivalent Matlab code to the accepted answer (you'll have to check if the resultant matrices are indeed diagonally dominant):

n = 5;
mmax = 100;
mat1 = 2*mmax*rand(n)-mmax;
mat = mat1+diag(sum(abs(mat1),2).*sign(diag(mat1)))
  • $\begingroup$ +1 I hadn't heard about gallery until now. Good to know about that function! $\endgroup$ – Luis Mendo Mar 9 '14 at 4:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.