通过向每个列向下滑动给定向量一步来创建矩阵

Moh*_*avi 3 matlab matrix vectorization

鉴于此向量

a = [1 2 3 4]
Run Code Online (Sandbox Code Playgroud)

我想创建一个像这样的矩阵

b = [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]
Run Code Online (Sandbox Code Playgroud)

以矢量化的方式不使用循环.

Lui*_*ndo 7

提示:使用conv2(悬停鼠标查看代码):

a = [1 2 3 4];
b = conv2(a(:), eye(numel(a)));

或者,在类似的情绪中,您可以使用convmtx(来自信号处理工具箱):

a = [1 2 3 4];
b = convmtx(a(:), numel(a));


the*_*alk 5

一种方法:

a = [1 2 3 4]
n = numel(a);

%// create circulant matrix from input vector
b = gallery('circul',[a zeros(1,n-1)]).' %'

%// crop the result
c = b(:,1:n)
Run Code Online (Sandbox Code Playgroud)

其他方式:

b = union( tril(toeplitz(a)), triu(toeplitz(fliplr(a))),'rows','stable')
Run Code Online (Sandbox Code Playgroud)

或其略有变化

b = union( toeplitz(a,a.*0),toeplitz(fliplr(a),a.*0).','rows','stable')
Run Code Online (Sandbox Code Playgroud)

甚至可能更快:

b = [ toeplitz(a,a.*0) ; toeplitz(fliplr(a),a.*0).' ]
b(numel(a),:) = []
Run Code Online (Sandbox Code Playgroud)

  • 我一直忘记'画廊'!+1 (3认同)