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)
以矢量化的方式不使用循环.
一种方法:
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)