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;
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With