如何在MATLAB中轻松创建以下矩阵?
A(nxn),B(nxp)和N是正整数。
Gamma = [B 0 0 ... 0 ;
A*B B 0 ... 0 ;
A^2*B A*B B ... 0 ;
... ... ... ... ... ;
A^(N-1)*B A^(N-2)*B A^(N-3)*B ... B];
答案 0 :(得分:3)
怎么样
[g{1:N,1:N}] = deal( zeros(n,p) );
g{1,1} = B;
for ii = 2:N
g( ii, 2:end ) = g( ii-1, 1:end-1 );
g{ ii, 1 } = A * g{ ii-1, 1 };
end
Gamma = cell2mat( g );
答案 1 :(得分:2)
虽然效率低于预期,但仍有效。
n = size(A,1);
p = size(B,2);
N = 3;
Gamma = zeros(N*n, N*p);
for ii = 1:N
for jj = 1:N
if ii >= jj
Gamma((ii-1)*n+1:ii*n,(jj-1)*p+1:jj*p) = A^(ii-jj) * B;
end
end
end
编辑:这是一个效率更高的版本,可以进行最少量的矩阵乘法。
n = size(A,1);
p = size(A,2);
N = 3;
Gamma = zeros(N*n, N*p);
# Pre-compute all the matrix multiplications we'll need.
memo = cell(1, N);
memo{1} = B;
for ii = 1:N-1
memo{ii+1} = A * memo{ii};
end
for ii = 1:N
for jj = 1:N
if ii >= jj
Gamma((ii-1)*n+1:ii*n,(jj-1)*p+1:jj*p) = memo{ii-jj+1};
end
end
end