gpt4 book ai didi

matlab - 在 MATLAB 中使用 repmat 复制 Kronecker 张量

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:05 27 4
gpt4 key购买 nike

我正在尝试仅使用 repmat 和 reshape 来复制 Kron 产品,我相信我已经非常接近了,但我无法完成最后一次正确的 reshape 。特别是我在 reshape A

时遇到问题

为简单起见,假设我们有

A=[1 3; 2 4]
B=[5 10; 10 5]

所以我的 kron(A,B) 将是一个 4x4 矩阵。

kron=[5   10  15  30
10 5 30 15
10 20 20 40
20 10 40 20]

我是这样处理的:

Y=repmat(B,2,2)
X=A(:);
X=repmat(X,1,2)';
X=X(:);
X=repmat(X,1,2);

这给了我以下 8x2 矩阵:

X= [1 1
1 1
2 2
2 2
3 3
3 3
4 4
4 4]

我不能只是弄清楚如何进行正确的 reshape 以获得我的 4x4 矩阵:

X=[1 1 3 3
1 1 3 3
2 2 4 4
2 2 4 4]

然后我将能够计算:X.*Y=kron(A,B)

最佳答案

这是使用强大的三重奏 bsxfun 的一种方法, permutereshape -

M = bsxfun(@times,B,permute(A,[3 4 1 2]));
out = reshape(permute(M,[1 3 2 4]),size(A,1)*size(B,1),[]);

如果你非常想使用repmat,用它来计算M,像这样-

M = repmat(B,[1 1 size(A)]).*permute(repmat(A,[1 1 size(B)]),[3 4 1 2])

通过与 kron 比较来验证输出对于通用矩阵大小 -

>> A = rand(4,5);
>> B = rand(6,7);
>> M = bsxfun(@times,B,permute(A,[3 4 1 2]));
>> out = reshape(permute(M,[1 3 2 4]),size(A,1)*size(B,1),[]);
>> out_kron = kron(A,B);
>> max(abs(out(:) - out_kron(:)))
ans =
0

这是一个使用 matrix-multiplication 的因此必须非常有效 -

[mA,nA] = size(A);
[mB,nB] = size(B);
out = reshape(permute(reshape(B(:)*A(:).',mB,nB,mA,nA),[1 3 2 4]),mA*mB,[])

关于matlab - 在 MATLAB 中使用 repmat 复制 Kronecker 张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33148653/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com