How to repeat diagonal vector in matlab

I would like to repeat a vector A length n diagonally m times to get the matrix (n+m-1) xm B For example, say A = [a;b;c;d] , m = 4 . This should lead to

 B = [a 0 0 0; ba 0 0; cba 0; dcba; 0 dcb; 0 0 dc; 0 0 0 d] 

Any suggestions on how to quickly achieve this? blkdiag(repmat(A,1,m)) does not help me in this case, as it creates a matrix (n*m) xm .

In the end, I'm just interested in the matrix product D third matrix C with B :

 D=C*B 

If you see another opportunity to get D without creating B , I would appreciate it. But solving the problem above would be very happy! n and m will be quite large.

Thanks!

+6
source share
3 answers

Awkward but overall single-line

 n = 3; %number of elements in A; m = 5; %repetitions A = (1:n); B = full( spdiags( repmat(A(:),1,m)' , 1-(1:n) , n+m-1, m) ) 

returns:

 B = 1 0 0 0 0 2 1 0 0 0 3 2 1 0 0 0 3 2 1 0 0 0 3 2 1 0 0 0 3 2 0 0 0 0 3 

Alternatively improved, general version of rubenvb solution

 B = toeplitz( [A(:);zeros(m-1,1)] , zeros(1,m) ) 

in both cases, A can be either a row or column vector.

A faster solution (2x ratio) is the first with spdiags !


Edit: even more inconvenient, but up to 10 times faster (it depends on n, m) than toeplitz -approach:

 B = reshape( [repmat([A(:);zeros(m,1)],m-1,1) ; A3(:)] ,[],m ) 
+5
source

Because @ mathematician1975 is too lazy to write the correct answer.

Matlab has a function for this called toeplitz

You would call it like this:

 c=[1;2;3;4;0;0;0]; r=[0, 0, 0, 0]; toeplitz(c,r) ans = 1 0 0 0 2 1 0 0 3 2 1 0 4 3 2 1 0 4 3 2 0 0 4 3 0 0 0 4 

You can play with zeros to form the matrix the way you want.

+7
source

A general solution without a matrix B is to convolve each row C from A you can do this for a loop:

 for k=1:size(C,1) D(k,:)=conv(C(k,:),A'); end D=D(:,length(A)-1:end-length(A)+1); % elliminate the convolution edges 

I think this can be done without a loop, arrayfun :

 k=1:size(C,1); D=arrayfun(@(x) conv(C(x,:),A'), k); D=D(:,length(A)-1:end-length(A)+1); % elliminate the convolution edges 
+2
source

All Articles