array operations consuming lower time

1 view (last 30 days)
Sara
Sara on 29 Aug 2012
Hi, we have an array x, I would like to do such a operation on it. It can be possible to implement it another way that consumes lower time?
y1y2 = x(2:n+2)+x(1:n+1) ;
Or is there any function to sum the two adjacent element of arrays? E.g., we want to add x(i) to x (i+1), for i=1 to n. and create the result as an array by the size of n-1. It means the i th element of new array is x(i)+x(i+1) .
Thanks in advance

Answers (2)

Daniel Shub
Daniel Shub on 29 Aug 2012
Edited: Daniel Shub on 29 Aug 2012
On my computer I can do a little better with conv...
>> x = randn(1e7, 1);
>> tic, y1y2 = x(2:end)+x(1:(end-1)); toc
Elapsed time is 0.330432 seconds.
>> tic, z1z2 = conv(x, [1,1], 'valid'); toc
Elapsed time is 0.166114 seconds.
>> isequal(y1y2, z1z2)
ans =
1
  1 Comment
Jan
Jan on 30 Aug 2012
Under Matlab 2009a both methods have the same speed. (Win7/64, DualCore)

Sign in to comment.


Jan
Jan on 29 Aug 2012
Edited: Jan on 30 Aug 2012
I'm curious about a speed comparison:
[EDITED, bugs fixed]
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
double *X, *Y, *XEnd, xi;
mwSize nX;
nX = mxGetNumberOfElements(prhs[0]);
X = mxGetPr(prhs[0]);
XEnd = X + nX;
plhs[0] = mxCreateDoubleMatrix(1, nX - 1, mxREAL);
Y = mxGetPr(plhs[0]);
xi = *X++;
while(X < XEnd) {
*Y++ = xi + *X;
xi = *X++;
}
return;
}
[EDITED, add timings]:
Matlab 2009a/64, Win7, Core2Duo:
tic, y1 = x(2:end)+x(1:(end-1)); toc
tic, y2 = conv(x, [1,1], 'valid'); toc
tic, y3 = addPairsMex(x); toc
isequal(y1, y2, y3)
Elapsed time is 0.276241 seconds.
Elapsed time is 0.265500 seconds.
Elapsed time is 0.095482 seconds.
1

Categories

Find more on Performance and Memory in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!