Cycles are not always slow. In fact, tests performed by Mathworks showed that loop speed improved by 40% as a result of the new and improved Execution Engine (JIT)
The average performance improvement in all tests was 40%. tests consisted of code that used a number of MATLAB products. Although not all applications ran faster with the redesign, most of them applications in R2015b are at least 10% faster than in R2015a.
and
The performance benefit of JIT compilation is most when MATLAB code is executed again and can reuse compiled code. This happens in normal cases, such as for-loops or when applications run extra time in a MATLAB session.
A quick test of three solutions:
%% bushmills answer, saved as bushmills.m function B = bushmills(A,N) B = zeros(size(A,1),size(A,2)/N); for i = 1:size(A,2)/NB(:,i) = mean(A(:,(i-1)*12+1:i*12),2); end end A = rand(1000,300); N = 12; %% Luis Mendo answer: lmendo = @(A,N) squeeze(mean(reshape(x.', N, size(x,2)/N, []))).'; %% Divakar answer: divakar = @(A,N) reshape(mean(reshape(A,size(A,1),N,[]),2),size(A,1),[]); b = @() bushmills(A,N); l = @() lmendo(A,N); d = @() divakar(A,N); sprintf('Bushmill: %d\nLuis Mendo: %d\nDivakar: %d', timeit(b), timeit(l), timeit(d)) ans = Bushmill: 1.102774e-03 Luis Mendo: 1.611329e-03 Divakar: 1.888878e-04 sprintf('Relative to fastest approach:\nDivakar: %0.5f\nBushmill: %0.5f\nLuis Mendo: %0.5f', 1, tb/td, tl/td) ans = Relative to fastest approach: Divakar: 1.00000 Bushmill: 5.34464 Luis Mendo: 10.73969
The loopback approach (with pre-distribution) is about 40% faster than squeeze(mean(reshape(...))) . Divakar's solution is a mile away.
It may differ for other values โโof A and N , but I have not tested everything.