gpt4 book ai didi

matlab - 计算张量的有效方法

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:43 24 4
gpt4 key购买 nike

假设 c 是一个 d 维向量。我想计算以下三阶张量 enter image description here

其中e_i代表欧氏空间的第i标准基。有没有一种有效的方法来计算这个?我正在使用以下 for 循环和 Kruskal-tensor ktensor 来使用 tensor toolbox 计算它由桑迪亚国家实验室管理:

x=ktensor({c,c,c});
I=eye(d);

for i=1:d
x=x+2*c(i)*ktensor({I(:,i),I(:,i),I(:,i)}
end

for i=1:d
for j=1:d

x=x- c(i)*c(j)*(ktensor({I(:,i),I(:,i),I(:,j)})+ktensor({I(:,i),I(:,j),I(:,i)})+ktensor({I(:,i),I(:,j),I(:,j)}))


end
end

最佳答案

这是一种可能性。

  • 我对第二项进行了优化,因为它将 c 的值沿张量的“对角线”放置。
  • 对于第一项,没有太多优化空间,因为它是密集乘法,所以 bsxfun 似乎是合适的。
  • 对于第三项,我坚持使用 bsxfun,但由于结果有点稀疏,如果矩阵的大小很大,您可能会受益于“手动”填充它。

代码如下:

dim = 10;
c = [1:dim]';
e = eye(dim);

x = zeros([dim, dim, dim]);
% initialize with second term
x(1:dim*(dim+1)+1:end) = 2 * c;
% add first term
x = x + bsxfun(@times, bsxfun(@times, c, shiftdim(c, -1)), shiftdim(c, -2));
% add third term
x = x - sum(sum(bsxfun(@times, shiftdim(c*c',-3), ...
bsxfun(@times, bsxfun(@times, permute(e, [1, 3, 4, 2, 5]), permute(e, [3, 1, 4, 2, 5])), permute(e, [3, 4, 1, 5, 2])) +...
bsxfun(@times, bsxfun(@times, permute(e, [1, 3, 4, 2, 5]), permute(e, [3, 1, 4, 5, 2])), permute(e, [3, 4, 1, 2, 5])) +...
bsxfun(@times, bsxfun(@times, permute(e, [1, 3, 4, 5, 2]), permute(e, [3, 1, 4, 2, 5])), permute(e, [3, 4, 1, 2, 5]))), 5), 4);

编辑

第三项的更有效(尤其是内存方面)计算:

ec = bsxfun(@times, e, c);
x = x - ...
bsxfun(@times, ec, shiftdim(c, -2)) -...
bsxfun(@times, c', reshape(ec, [dim, 1, dim])) -....
bsxfun(@times, c, reshape(ec, [1, dim, dim]));

关于matlab - 计算张量的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44829751/

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