MATLAB: Arrayfun application to avoid a FOR loop

arrayfunarraysMATLAB

Hi everyone,
The question pertains to the use of arrayfun. I'm interested in using corrcoef on a series of arrays. So far what I have is:
% Create two variables.
alpha = rand([5 6 10]);
beta = rand([5 6 10]);
% Run the loop through to generate the correlation coefficients.
for n = 1:size(alpha,3)
gamma(:,:,n) = corrcoef(alpha(:,:,n), beta(:,:,n));
end
Looking at this, I'm thinking that I should be able to apply arrayfun for cases where the size of the arrays become significantly larger. I tried:
fun = @(A,B) corrcoef(A,B);
iota = arrayfun(fun,alpha,beta)
But all I seem to unfortunately get is a series of arrays with ones.
Would anyone be able to advise on the correct implementation?
Thanks in advance.

Best Answer

You can replace
for n = 1:size(alpha,3)
gamma(:,:,n) = corrcoef(alpha(:,:,n), beta(:,:,n));
end
with
gamma=cell2mat(arrayfun(@(n) corrcoef(alpha(:,:,n), beta(:,:,n)), ...
reshape(1:size(alpha,3),1,1,[]), ...
'UniformOutput',false));
Being able to send an operation like this to arrayfun, clearly indicates that the operation is highly parallelizable and one might think that under the hood arrayfun is using some sort of parallelization or multi-threading (at least I was trusting MATHWORKS is doing this). It really doesn't make any sense not to take advantage of such condition.
However, it has brought to my attention that actually once you are using only CPU, arrayfun is no different than writing loop (or it might be even slower).