Arrayfun application to avoid a FOR loop
Mostrar comentarios más antiguos
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.
2 comentarios
Sid
el 6 de Oct. de 2015
Movida: Dyuman Joshi
el 6 de Abr. de 2024
Mohammad Abouali
el 6 de Oct. de 2015
Movida: Dyuman Joshi
el 6 de Abr. de 2024
You are welcome.
For larger arrays, regular for-loop might be actually faster than arrayfun. If you decided to keep the regular for-loop just make sure to initialize the gamma before entering the loop. (with arrayfun, you don't need to do that)
Respuesta aceptada
Más respuestas (1)
Steven Lord
el 6 de Oct. de 2015
1 voto
Your code is going to iterate through the scalar elements of alpha and beta. What you want is to iterate through the pages of the 3-D arrays alpha and beta. Consider what @(n) alpha(:, :, n) does and you should see over which (one) array your ARRAYFUN call should iterate.
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!