From: Oleg Komarov on
"Cris Luengo" <cris.luengo(a)google.for.my.name.to.contact.me> wrote in message <i1hcf7$p0r$1(a)fred.mathworks.com>...
> "Oleg Komarov" <oleg.komarovRemove.this(a)hotmail.it> wrote in message <i1habo$dfn$1(a)fred.mathworks.com>...
> > N = 256; x = randn(N,N,N);
> >
> > % Elapsed time is 0.546098 seconds.
> > tic; y = 0.5*( x(:,:,1:N-1) + x(:,:,2:N)); toc
> >
> > % Elapsed time is 0.301945 seconds.
> > tic; y1 = reshape((reshape(x(:,:,1:N-1),1,[]) + reshape(x(:,:,2:N),1,[]))*.5,256,256,[]); toc
>
> Oleg,
> I'm baffled as to why the reshaped arrays compute faster. I tried it, it is faster, I just don't see why. Please enlighten me!
> Cheers,
> Cris.

Unfortunately I can't give you a detailed explanation but the point is that when
ndims(x) > 2 I've seen often that the code isn't optimized (which you can't see for sum or '+').
I hope anybody else can answer you with more details...

Oleg
From: Sukanta on
Thanks a lot folks for all the suggestions. I appreciate it. I am also puzzled by the fact that an explicit for-loop reduces the cost.

tic; y = 0.5*( x(:,:,1:N-1) + x(:,:,2:N)); toc
Elapsed time is 0.294341 seconds.

tic; y = zeros(N,N,N-1); for k = 1:N-1; y(:,:,k) = 0.5*(x(:,:,k)+x(:,:,k+1)); end; toc
Elapsed time is 0.235350 seconds.

tic; y1 = reshape((reshape(x(:,:,1:N-1),1,[]) + reshape(x(:,:,2:N),1,[]))*.5,N,N,[]);toc
Elapsed time is 0.210588 seconds.

"Oleg Komarov" <oleg.komarovRemove.this(a)hotmail.it> wrote in message <i1hdu4$pvg$1(a)fred.mathworks.com>...
> "Cris Luengo" <cris.luengo(a)google.for.my.name.to.contact.me> wrote in message <i1hcf7$p0r$1(a)fred.mathworks.com>...
> > "Oleg Komarov" <oleg.komarovRemove.this(a)hotmail.it> wrote in message <i1habo$dfn$1(a)fred.mathworks.com>...
> > > N = 256; x = randn(N,N,N);
> > >
> > > % Elapsed time is 0.546098 seconds.
> > > tic; y = 0.5*( x(:,:,1:N-1) + x(:,:,2:N)); toc
> > >
> > > % Elapsed time is 0.301945 seconds.
> > > tic; y1 = reshape((reshape(x(:,:,1:N-1),1,[]) + reshape(x(:,:,2:N),1,[]))*.5,256,256,[]); toc
> >
> > Oleg,
> > I'm baffled as to why the reshaped arrays compute faster. I tried it, it is faster, I just don't see why. Please enlighten me!
> > Cheers,
> > Cris.
>
> Unfortunately I can't give you a detailed explanation but the point is that when
> ndims(x) > 2 I've seen often that the code isn't optimized (which you can't see for sum or '+').
> I hope anybody else can answer you with more details...
>
> Oleg