array operations consuming lower time

1 次查看(过去 30 天)
Sara
Sara 2012-8-29
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

回答(2 个)

Daniel Shub
Daniel Shub 2012-8-29
编辑:Daniel Shub 2012-8-29
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 个评论
Jan
Jan 2012-8-30
Under Matlab 2009a both methods have the same speed. (Win7/64, DualCore)

请先登录,再进行评论。


Jan
Jan 2012-8-29
编辑:Jan 2012-8-30
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

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by