在循环外做重复计算,不够好。该怎么办?

时间:2015-10-15 18:25:58

标签: matlab for-loop memory-management vectorization

我有如下功能。此函数将用于for循环。在循环中,仅在每次迭代中更改变量s,并且向量k1k2kt1kt2是常量。因为对我来说在很短的时间内完成计算很重要,所以我不想计算与每次迭代中的常量向量相关的相同事物。因此,我可以在循环之前执行与向量k1k2kt1kt2相关的计算。这样,在for循环的每次迭代中,我只需要计算out2然后计算outeachkt,因为它们需要s

问题是,为了做我说的话,我必须保存所有其他变量并在for循环中使用它们。保存这些变量,尤其是out1需要占用大量内存,这真的让我的笔记本电脑变得很慢。

你有什么建议吗?

function eachkt = wholekt(k1,k2,kt1,kt2,s)

k1 = k1(:); k2=k2(:); kt1=kt1(:); kt2=kt2(:);
% k1_kbs1 = repmat(k1,1,numel(kt1))-repmat(kt1',numel(k1),1);
k1_kbs1 = bsxfun(@minus,k1,kt1');
% k2_kbs2 = repmat(k2,1,numel(kt2))-repmat(kt2',numel(k2),1);
k2_kbs2 = bsxfun(@minus,k2,kt2');
fork1 = bsxfun(@rdivide,prod(k1_kbs1,2),k1_kbs1);
[row, col] = find(isnan(fork1)); fork1(row,col)= eps;
fork2 = bsxfun(@rdivide,prod(k2_kbs2,2),k2_kbs2);
[row, col] = find(isnan(fork2)); fork2(row,col)= eps;
N1 = size(fork1,1);
N2 = size(fork2,1);
% foreachk = zeros(N1,N2,size(fork1,2)^2);
% D = reshape(bsxfun(@times,permute(fork1,[1 3 2]),fork2(:).'),N1,N2,[]);
out1 = reshape(bsxfun(@times,permute(fork1,[1 4 2 3]),permute(fork2,[4 1 3 2])),N1,N2,[]);
out2 = bsxfun(@times,out1,s);
out = reshape(sum(sum(out2,1),2),numel(kt1),numel(kt2));

a = 1./prod(bsxfun(@minus,kt1,kt1')+ eye(numel(kt1)),2);
b = 1./prod(bsxfun(@minus,kt2,kt2')+ eye(numel(kt2)),2);
c = a*b';
eachkt = c.*out ;


return

以下是一个例子:

k1 = rand(1,30);
k2 = rand(1,30);
kt1 = rand(1,10);
kt2 = rand(1,10);

for j = 1:100
    s = rand(30,30);
    eachkt = wholekt(k1,k2,kt1,kt2,s);
 end

0 个答案:

没有答案