2
votes

I have a vector, where each value corresponds to a diagonal. I want to create a matrix from this vector. I have a code:

x = [1:5];
N = numel(x);
diagM = diag(repmat(x(1),N,1),0);
for iD = 2:N
    d = repmat(x(iD),N-iD+1,1);
    d_pos = diag(d,iD-1);
    d_neg = diag(d,-iD+1);
    d_join = d_pos+d_neg;
    diagM = diagM+d_join;
end

It gives me what i want:

diagM =

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

But it becames really slow, for example for x=[1:10^4].

Could You help me with another FASTER way to generate such a sequence?

1

1 Answers

4
votes

Use toeplitz:

x = 1:5;
diagM = toeplitz(x);

Or do it manually, vectorized:

x = 1:5;
t = 1:numel(x);
diagM = x(abs(t-t.')+1); % x(abs(bsxfun(@minus, t, t.'))+1) in old Matlab versions