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%的速度提升。我如何也向量化外部循环?
发布于 2013-06-27 23:52:03
您可能正在寻找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 herehttps://stackoverflow.com/questions/17345936
复制相似问题