array operations consuming lower time
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (2)
Daniel Shub
le 29 Août 2012
Modifié(e) : Daniel Shub
le 29 Août 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 commentaire
Jan
le 29 Août 2012
Modifié(e) : Jan
le 30 Août 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
0 commentaires
Voir également
Catégories
En savoir plus sur Performance and Memory dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!