Matlab中重复元素矩阵的优化矩阵运算

时间:2015-09-02 16:57:04

标签: matlab matrix sparse-matrix

我想得到一个大矩阵(A)的exp(),其值在不同的索引处重复。为了加速exp()操作,我只在A的唯一值上执行它,然后重新组装矩阵。然而,矩阵的重组非常慢。以下代码提供了一个工作示例:

% defintion of a grid
gridSp = 5:5:35*5;

X = repmat(gridSp,35,1);
Z = repmat(gridSp',1,35);

% calculation of the distances
locMat = [X(:) Z(:)];
dist=sqrt(bsxfun(@minus,locMat(:,1),locMat(:,1)').^2 +...
bsxfun(@minus,locMat(:,2),locMat(:,2)').^2); 

sizeDist = size(dist);
uniqueDist = unique(dist,'stable');
[~, Locb] = ismember(dist,uniqueDist);

nn_A = exp(1i*2*pi*rand(sizeDist(1),100));
H_A = zeros(size(nn_A));

freq = linspace(10^-3,10,100);

psdA = 4096*length(freq).*10.*4.*22.6./((1 + 6.*freq*22.6).^(5/3));

for jj=1:100 
    b = exp(-8.8*uniqueDist*sqrt((freq(jj)/15).^2 + 10^-7));
    b = b.*psdA(jj);
    A = b(Locb);
    droptol = max(A(:))*10^-10;
    if min(A(:))<droptol
        A = sparse(A);
        HH_A = ichol(A,struct('type','ict','shape','lower','droptol',droptol));
    else
        HH_A = chol(A,'lower');
    end
    H_A(:,jj) = HH_A*nn_A(:,jj);
end

特别是矩阵的重组

A = b(Locb);

并将矩阵转换为稀疏

A = sparse(A);

在最后一个for循环中占用了大量时间。有更快的方法吗?有趣的是:

B = A + A;

快得多
A = b(Locb);

我必须经常执行这些操作,而不是示例中的100次迭代。

这是代码的精简版本(请参阅下文)。

% defintion of a grid
gridSp = 5:5:28*5;

X = repmat(gridSp,35,1);
Z = repmat(gridSp',1,35);

% calculation of the distances
locMat = [X(:) Z(:)];
dist=sqrt(bsxfun(@minus,locMat(:,1),locMat(:,1)').^2 +bsxfun(@minus,locMat(:,2),locMat(:,2)').^2); 

uniqueDist = unique(dist,'stable');
[~, Locb] = ismember(dist,uniqueDist);

for jj=1:100 
    b = exp(jj.*uniqueDist);
    A = b(Locb);
end

1 个答案:

答案 0 :(得分:0)

在你的例子中,dist的维度只有980 x 980,在这种情况下你最好只执行密集矩阵运算,即

server.R

快2倍
for jj=1:100
   A=exp(jj*dist);
end

您的例子。