Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab sum(X-Y) vs sum(X) - sum(Y)

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?

like image 950
niceman Avatar asked Nov 30 '22 17:11

niceman


1 Answers

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')

enter image description here

like image 188
Sam Roberts Avatar answered Dec 04 '22 12:12

Sam Roberts