Search code examples
matlabbsxfun

Matlab Vectorising matrix subtraction using bsxfun


I have an array Y=rand(1000,28); I want to find the columnwise difference thus:

[~ c]=size(Y);

for i=1:c-1
Y(:,i)-Y(:,i+1)
end

Can I do this using bsxfun?


Solution

  • You can also do this using the function diff:

    dY = -diff(Y, [], 2)
    

    The [] and 2 tell diff to operate along the second dimension of Y, as specified in your question.

    Note that this is actually faster, because diff is a built-in function:

    >> Y = rand(100, 10000);
    >> tic; for n = 1:1000; dY = -diff(Y, [] , 2); end; toc
    Elapsed time is 5.453160 seconds.
    >> tic; for n = 1:1000; dY = Y(:,1:end-1) - Y(:,2:end); end; toc
    Elapsed time is 11.383666 seconds.
    

    Edit: It has been suggested to use the timeit function to calculate these timings more accurately; the results are:

    >> timeit(@()-diff(Y, [] , 2))
    
    ans =
    
        0.0071
    
    >> timeit(@()Y(:,1:end-1) - Y(:,2:end))
    
    ans =
    
        0.0119
    

    Also, putting these in an m-file appears not to make a difference in this case.