我有这两种不同的方法来实现相同的东西,但我想第二种是最好的。但是,第一次使用 tic toc 时我得到了更好的结果。怎么会 ?
j=6;
i=j;
Savings = zeros(i,j);
Costs = magic(400);
tic;
for x=2:i
for y=2:j
if(x ~= y)
Savings(x,y) = Costs(x,1) + Costs(1,y) - Costs(x,y);
end
end
end
first=toc;
disp(num2str(first))
Savings = zeros(i,j);
tic;
Ix=2:i;
Iy=2:j;
I = false(i,j);
I(Ix,Iy) = bsxfun(@ne, Ix', Iy);
S = bsxfun(@plus, Costs(Ix,1), Costs(1,Iy)) - Costs(Ix,Iy);
Savings(I) = S(I(Ix,Iy));
second=toc;
temp = Savings;
disp(num2str(second))