How would i vectorize that 'for' loop in Matlab? -


i have toy example:

l = [1, 2, 3, 4, 5]; = zeros(3, 1); p = 1:3     a(p) = sum(l(p:p+2)); end; 

this example calculates sum of each 3 elements in 'l', close each other , writes in 'a'. now, possible rewrite same code using vectorization , matrix operations, without 'for' loop? have tried similar to:

p = 1:3; a(p) = sum(l(p:p+2)); 

the result [6, 6, 6], have calculated sum of first 3 elements , wrote in 'a' on each position. toy example, need similar on 3d 256x256x128 array 20x20x20 cube elements sum, using 'for' loops slow there. so, there fast way solve problem?

edit : divakar have suggested me use actual case here. well, here important part of it, trying rewrite:

edit2 : thank answer. understood idea, removed code above, rewriting now.

you're describing basic convolution:

a = conv(l,ones(1,3),'valid'); % should have 3 elements 

for 3d, use convn in similar fashion ones(20,20,20)


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -