假设A是n_1乘n_1对称矩阵,B是n_2乘n_2对称矩阵,其中n_1> n_1。 n_2和n_1是10 ^ 3到10 ^ 5。我希望通过(n_1 * n_2)矩阵C获得以下(n_1 * n_2),使得C的每个块都是C_ {ij} = \ exp(A \ text {。^} 2 / B_ {i,j} ^ {1.5})/ B_ {i,j},i = 1,...,n_2; j = 1,...,n_2。
我有两种方法可以在MATLAB中计算它,但这两种方法都没有给我满意的时机。在下文中,我将在MATLAB代码中给出一个最小的例子。
n1 = 400; n2 = 15;
A = randn(n1); A = A + A' + 10*eye(n1);
B = randn(n2); B = B + B' + 5*eye(n2);
一种方式:
tic;
Atemp = repmat(A, n2, n2);
Btemp = kron(B, ones(n1));
C1 = exp(Atemp.^2./Btemp.^1.5)./Btemp;
toc;
Elapsed time is 2.402167 seconds.
另一种方式:
tic;
Btemp = reshape(B, [1 1 n2*n2]);
Ctemp = bsxfun(@(x,y) exp(x.^2/y.^1.5)/y, A, Btemp);
[a, b, c] = size(Ctemp);
Ctemp = reshape(mat2cell(Ctemp, a, b, ones(c,1)), sqrt(c), sqrt(c));
C2 = cell2mat(Ctemp);
toc;
Elapsed time is 2.923428 seconds.
我想知道是否有更有效的方法在MATLAB中获取矩阵C?胆甾醇分解需要所得的基质C.
BTW,在第二种方法中,必须有更有效的方法(即避免将Ctemp转换为单元,然后将单元转换为C2)以将3维数组Ctemp转换为2维数组C2,但我无法弄明白现在非常感谢!
答案 0 :(得分:0)
bsxfun
通常没有您期望的那么快。细胞/垫重塑也需要一些时间。所以你的第一种方法更好。但Atemp.^2./Btemp.^1.5
可以简化为kron(1./(B.^1.5), A.^2)
,以避免某些大型时间矩阵并提高速度。
这是修改后的代码和我机器上的时间。
n1 = 400; n2 = 15;
A = randn(n1); A = A + A' + 10*eye(n1);
B = randn(n2); B = B + B' + 5*eye(n2);
tic;
Btemp = kron(B, ones(n1));
C0 = exp(kron(1./(B.^1.5), A.^2))./Btemp;
toc;
tic;
Atemp = repmat(A, n2, n2);
Btemp = kron(B, ones(n1));
C1 = exp(Atemp.^2./Btemp.^1.5)./Btemp;
toc;
tic;
Btemp = reshape(B, [1 1 n2*n2]);
Ctemp = bsxfun(@(x,y) exp(x.^2/y.^1.5)/y, A, Btemp);
toc;
tic;
[a, b, c] = size(Ctemp);
Ctemp = reshape(mat2cell(Ctemp, a, b, ones(c,1)), sqrt(c), sqrt(c));
C2 = cell2mat(Ctemp);
toc;
Elapsed time is 0.426900 seconds.
Elapsed time is 0.900966 seconds.
Elapsed time is 2.850293 seconds.
Elapsed time is 0.706957 seconds.