The art of vectorizing – Part 2

In a previous post, I introduced you how to the art of vectorize your code. Here I continue in this serie and present some additional tips. I show how to use repmat to process series of elements all at once.

As a neuroscientist, it often came to me that I had to process multiple time traces. Each one of these time traces was an individual trial of the same experiment. So my data matrix Trials was N by T where N is the number of repetition and T the number of time points. A very common thing to do is to substract the average over time from each trial. With for loops you would do :

for i=1:N

To vectorize this code, you first need to get an average matrix. You need to process all the trials at the same time. mean is quite handy for that as mean(Trials,2) will average all the rows and create a column of all the average.
Once you have the average, you face the problem that Trials is a big matrix, so you need to recreate a big average matrix of the same size. repmat is just what you need. It will duplicate your average column over all the T time points.

For instance with A=[1 2 3], repmat(A,2,1) will be

1 2 3
1 2 3

Using repmat, the vectorized version of this for loop is :


Related Posts

This entry was posted in Intermediate, Optimizing your code. Bookmark the permalink.

7 Responses to The art of vectorizing – Part 2

  1. Nick S says:

    I think you can do better here with bsxfun. At least for this particular example, I get the following:

    >> a = rand(1000,10000);
    >> tic; mn = mean(a,2); mnrep = repmat(mn, 1,size(a,2)); res1 = a-mnrep; toc
    Elapsed time is 0.164605 seconds.
    >> tic; res2 = bsxfun(@minus, a, mean(a,2));toc;
    Elapsed time is 0.105141 seconds.

    (res1 and res2 are identical).


  2. arijithazra says:

    Is there any way we can vectorize matlab for loop involving ode solver at each step and multi-dimensional matrix e.g.

    M0=repmat([0 0 1],p,1)';
    for p=1:ns
    [t,M(:,:,p)]=ode45(@(t,M) testfun(t,M,dw(p)),tspan,M0(:,p));

  3. arijithazra says:


    function dM=testfun(t,M,w1)

    • Jerome says:

      I am not sure you can do this straight with matrices. Maybe with Cell if you convert each ‘frame’ to a cell element.
      Have you looked into cellfun?

  4. John Franklin Ruiz Neira says:

    Can some one helpme to vectorizing this section code:

    for i=1:alto
    for j=1:ancho
    if E~=0

Leave a Reply