Home > Software engineering >  How do I create a symmetric matrix with a linearly decreasing diagonal in MatLab?
How do I create a symmetric matrix with a linearly decreasing diagonal in MatLab?

Time:04-08

I'm trying to create a symmetric n by n matrix where the symmetry line is linearly decreasing from n to 1.

For example a 5 by 5 would be:

5 4 3 2 1 
4 4 3 2 1
3 3 3 2 1
2 2 2 2 1
1 1 1 1 1 

Thanks

CodePudding user response:

Using implicit expansion, the min function will generate a square matrix from the combination of a row and a column vector, so the result can be gained by doing:

N = 5;
A = min( (N:-1:1).', (N:-1:1) );

CodePudding user response:

You may use:

numRows = 5;

mI = repmat((1:numRows)', 1, numRows);
mJ = repmat((1:numRows), numRows, 1);

mA = flip(flip(min(mI, mJ), 1), 2)

With the answer given by:

mA =

     5     4     3     2     1
     4     4     3     2     1
     3     3     3     2     1
     2     2     2     2     1
     1     1     1     1     1

  • Related