If we have two matrices X
and Y
, both two-dimensional, now mathematically we can say: sum(X-Y)=sum(X)-sum(Y)
.
Which is more efficient in Matlab? Which is faster?
On my machine, sum(x-y)
is slightly faster for small arrays, but sum(x)-sum(y)
is quite a lot faster for larger arrays. To benchmark, I'm using MATLAB R2015a on a Windows 7 machine with 32GB memory.
n = ceil(logspace(0,4,25));
for i = 1:numel(n)
x = rand(n(i));
y = rand(n(i));
t1(i) = timeit(@()sum(x-y));
t2(i) = timeit(@()sum(x)-sum(y));
clear x y
end
figure; hold on
plot(n, t1)
plot(n, t2)
legend({'sum(x-y)', 'sum(x)-sum(y)'})
xlabel('n'); ylabel('time')
set(gca, 'XScale', 'log', 'YScale', 'log')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With