Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab decreasing matrix diagonal

I want to create a matrix where the middle diagonal is symmetrically decreasing to the sides, like this:

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

The matrix has to be 100x100 and the values are between 0 and 1. Until now I only get the edges and the middle diagonal, but can't get the idea on how to automatically fill the rest.

v = ones(1,100);
green = diag(v);
green(:,1) = fliplr(0:1/99:1);
green(1,:) = fliplr(0:1/99:1);
green(100,:) = 0:1/99:1;
green(:,100) = 0:1/99:1;
like image 242
Benny Müller Avatar asked Nov 01 '15 12:11

Benny Müller


People also ask

How do you create a diagonal matrix in Matlab?

D = diag( v ) returns a square diagonal matrix with the elements of vector v on the main diagonal. D = diag( v , k ) places the elements of vector v on the k th diagonal. k=0 represents the main diagonal, k>0 is above the main diagonal, and k<0 is below the main diagonal.

How do you convert a matrix into a lower triangular matrix in Matlab?

L = tril( A ) returns the lower triangular portion of matrix A . L = tril( A , k ) returns the elements on and below the kth diagonal of A .


1 Answers

To look for a vectorized solution consider using spdiags().

n = 5;
A = repmat([1:n-1,n:-1:1],n,1);
B = full(spdiags(A,-n+1:n-1,n,n));

This will return:

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

As @Adriaan pointed out B = B/n will transform the matrix values between 0 and 1.

like image 102
Dennis Klopfer Avatar answered Oct 20 '22 22:10

Dennis Klopfer