# How to create a square matrix with zero on main diagonal and all 1's, 2's, 3's, ... n's on upper and lower diagonals?

20 views (last 30 days)
Kelsey Allis on 1 Feb 2021
Edited: Kelsey Allis on 1 Feb 2021
Hello,
I have to create a square matrix using a diag function that has the pattern:
m = [ 0 1 2 3 4.... ;
1 0 1 2 3 .... ;
2 1 0 1 2 ....]
The issue is with the line m = m + diag(n, i). It doesn't have the right dimensions. Any feedback would be appreciated!
function m = matpat(n)
%UNTITLED5 Summary of this function goes here
% Function creates an n x n matrix with a pattern of 0 on main diagonal,
% and all 1s, 2s, 3s, ... on upper and lower diagonals
m = zeros(n) ;
for i = 1 : (n - 1)
m = m + diag(n , i) ;
end

madhan ravi on 1 Feb 2021
help toeplitz
TOEPLITZ Toeplitz matrix. TOEPLITZ(C,R) is a non-symmetric Toeplitz matrix having C as its first column and R as its first row. TOEPLITZ(R) is a symmetric Toeplitz matrix for real R. For a complex vector R with a real first element, T = toeplitz(r) returns the Hermitian Toeplitz matrix formed from R. When the first element of R is not real, the resulting matrix is Hermitian off the main diagonal, i.e., T_{i,j} = conj(T_{j,i}) for i ~= j. Class support for inputs C,R: float: double, single integer: uint8, int8, uint16, int16, uint32, int32, uint64, int64 See also HANKEL. Documentation for toeplitz doc toeplitz Other functions named toeplitz distributed/toeplitz sym/toeplitz
##### 1 CommentShowHide None
Kelsey Allis on 1 Feb 2021
I have to use the diag function for this excercise, so the toeplitz doesn't help me in this case. Thank you though.