Search code examples
matlabloopsfor-loopmatrixsubmatrix

MATLAB: How to calculate (on) Submatrices without a loop


I want to split a matrix columnwise into 3 segments and do a calculation on it (mean()). Is there a way to get this without a for-loop, as I did in this provided sample?

M = [2 4 9; 50 50 200; 30 0 0];
M = [M 10*M]
N = length(M);
seg = 3 % split in lets say 3 parts
segLen = round(N/seg)
segBeg = (((1:seg)-1) * segLen)+1  % start indices
segEnd = segBeg + segLen -1        % end indices

for i = 1: length(segBeg)
    mean(M(:,segBeg(i):segEnd(i)),2)
end

Thank you!


Solution

  • Think outside the box: use the 3rd dimension:

    r=reshape(M,size(M,1),segLen,[])
    squeeze(mean(r,2))
    

    The first line produces a 3d array with the first matrix at r(:,:,1), the second at r(:,:,2), ... (use M(:,1:seg*segLen) instread of M if the number of columns is not divisible by segLen). mean(r,2) produces a nrows-by-1-by-seg array, squeeze makes a nrows-by-seg matrix out of it again.