0
y = 0;

for m = 0:variable
  for n = 0:m
    y = y + f(n,m);
  end
end

I vectorized the inner loop this way,

y = 0;

for m = 0:variable
  n = 0:m
  y = y + f(n,m);
end

This resulted in around 60% speed increase for my code. How do I also vectorize the outer loop?

4

1 回答 1

2

您可能正在寻找该meshgrid功能。它旨在填充您需要的 m x n 组合。例如:

>> m = 1:4;
>> n = 1:3;
>> [mGridValues, nGridValues] = meshgrid(m,n)
mGridValues =
     1     2     3     4
     1     2     3     4
     1     2     3     4
nGridValues =
     1     1     1     1
     2     2     2     2
     3     3     3     3

这有点复杂,因为您的内循环取决于外循环的值。所以你需要屏蔽掉不需要的 [n, m] 对(见下文)。

修改您提供的原型代码,您最终会得到如下内容:

[mValues, nValues] = meshgrid(0:variable, 0:variable);  %Start with a full combination of values

mask = mValues >= nValues;  %Identify all values where m >= n
mValues = mValues(mask);    %    And then remove pairs which do not
nValues = nValues(mask);    %    meet this criteria

y = f(nValues, mValues );   %Perform whatever work you are performing here
于 2013-06-27T15:52:02.700 回答