SeanBeggan
SeanBeggan

Reputation: 11

How do I create a symmetric matrix with a linearly decreasing diagonal in MatLab?

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

Upvotes: 1

Views: 66

Answers (2)

Wolfie
Wolfie

Reputation: 30047

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) );

Upvotes: 2

Royi
Royi

Reputation: 4953

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

Upvotes: 1

Related Questions