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 AverageValue=mean(Trials(i,:)); Trials(i,:)=Trials(i,:)-AverageValue; end
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 :
AverageValue=mean(Trials,2); ReplicatedAverage=repmat(AverageValue,1,T); Trials=Trials-ReplicatedAverage;