Minh Nghĩa
Minh Nghĩa

Reputation: 1053

Matlab: slower execution although less operation

I'm new to Matlab. This is my playground script:

function speedtest()
    a = reshape(1:1:30000, 10000, 3);

    tic;
    for i = 1:100
        a(:, [1, 2]) = bsxfun(@minus, a(:, [1, 2]), [1, 1]);
    end
    toc

    tic;
    for i = 1:100
        a = bsxfun(@minus, a, [1, 1, 0]);
    end
    toc
end

And the execution time:

Elapsed time is 0.007709 seconds.
Elapsed time is 0.001803 seconds.

The first method has less operation, but it runs much slower. Is this a vectorization issue? If so, why can't Matlab "vectorize" my a(:, [1, 2]) selection?

Update:

As per @thewaywewalk, I put the code to individual function, remove the loop and use timeit. Here's the result:

# a(:, [1, 2]) = bsxfun(@minus, a(:, [1, 2]), [1, 1]);
1.0064e-04

# a = bsxfun(@minus, a, [1, 1, 0]);
6.4187e-05

Upvotes: 1

Views: 47

Answers (1)

FangQ
FangQ

Reputation: 1544

the overhead of the first approach came from sub-matrix slicing. changing it to

    tic;
    b=a(:,[1,2]);
    for i = 1:100
        b = bsxfun(@minus, b, [1, 1]);
    end
    a(:,[1,2])=b;
    toc

makes it significantly faster

Upvotes: 1

Related Questions