MATLAB: Subtracting mean of columns from corresponding columns in 3d matrix

baseline correctionfor loopfunctionsmatrix manipulationmean

Hi!
I am trying to use a for loop in a function to subtract the mean value (baseline) of column 1:51 for 64 rows, and subtract this value from the corresponding columns. The matrix (epochs_CG) is 64x250x586. So for example, for epochs_CG (1, 1:51, 1) the baseline = mean (epochs_CG (1, 1:51, 1)), and the baseline corrected epoch for that channel (row) is epochs_CG(1, 1:51, 1) – baseline.
However, I need to do this calculation in a loop so it can subtract the baseline from the for all the rows and for all the different epochs, but I just can't seem to get it right. Here is my function so far; Somehow, I'm
function epochs = baselineCorr(epochs, startT)
Fs = 250; % Sampling Frequency (Hz)
Ts = 1/Fs; % Sampling Interval (s)
startIdx = floor(startT / (Ts * 1E+3)); % Start Index
for i = 1:length(epochs)
baseline = mean(epochs(:,51+startIdx:51,i),2);
epochs(:,51+startIdx:51,:) = epochs(:,51+startIdx:51,:) - baseline ;
end
This does not seem to be doing what i want it to do 😛 Would appreciate any help!

Best Answer

Try this, is the result the expected one?
epochs = rand([64,250,586]);
col = 51;
baseline = mean(mean(epochs(:,1:col,:),1),2);
epochs(:,1:col,:) = epochs(:,1:col,:)-repmat(baseline,size(epochs,1),col,1);