2

I have a 3D array M(d*d,m,n). For each d*d vector of M (i.e. vectors of the first dimension), I split it into d parts and take the sum of each part to form a new vector (of size d). For example, if u is a vector along the first dimension of M, then it will be replaced by the vector v, computed by:

v = sum(reshape(u,d,d))';

For the moment I use a loop as following, but I think there should be a much faster way to do it.

N = zeros(d,m,n)
for i=1:m
    for j=1:n
        N(:,i,j) = sum(reshape(M(:,i,j),d,d))'; %//'
    end
end

Thank you so much for any suggestions!

2 Answers 2

3

Try this -

N = reshape(sum(reshape(M,d,[])),d,m,n)
Sign up to request clarification or add additional context in comments.

Comments

3

I may not be understanding the question correctly but is this what you are looking for?

N=squeeze(sum(reshape(M,[d,d,size(M,2),size(M,3)])))

6 Comments

Btw: Both answers are similar fast :)
@matheburg Seems like you are doing benchmarks around here, which is great, keep 'em coming! :)
Thanks :) In my view it is really important. The only reason I want to vectorize anything is the speed-up, isn't it? I am usually implementing huge simulations where speed and memory optimization is really important. Today I have a day off ;-)
@matheburg haha nice, SO is lucky to have you today ;) Agreed that speedup should be the primary reason for vectorization! Well MATLAB is coming off age with its PCT to speed things up. I really hope they talk more of the GPU when speeding things up here on SO, which they don't sadly.
Hi ASantosRibeiro and @Divakar. Thank you very much for your answers. I tested both solutions and ASantosRibeiro's one is slightly faster (but the difference is very small). Since Divakar posted his answer first and also suggested a correction to ASantosRibeiro's, I think credits should go to him first. (I wish I could mark both as answers :( )
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.