y = 0;
for m = 0:variable
for n = 0:m
y = y + f(n,m);
end
end
我用这种方式对内循环进行了矢量化,
y = 0;
for m = 0:variable
n = 0:m
y = y + f(n,m);
end
这导致我的代码速度提高了约60%。我如何对外循环进行矢量化?
答案 0 :(得分:2)
您可能正在寻找meshgrid
功能。它旨在填充您需要的m种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