Is there a faster way to cube a array?

11 views (last 30 days)
Hi everyone
I have an array A whose size is 80000 x 4 x 4.
In order to calculate the cube of each element of A, I am doing
B=A.*A.*A;
Is there a faster way to calculate the cube of each element? Thanks in advance,
  2 Comments
KSSV
KSSV on 12 Feb 2021
B = A.^3 ;
But looks what you have tried takes less time..
Ram Kishore Arumugam
Ram Kishore Arumugam on 12 Feb 2021
Thanks @KSSV. Yeah you are correct. A.^3 is a bit slower.

Sign in to comment.

Accepted Answer

Jan
Jan on 12 Feb 2021
Edited: Jan on 12 Feb 2021
On my i5, Matlab R2018b:
tic; y = x.^3; toc
% Elapsed time is 0.109015 seconds.
tic; y = x.*x.*x; toc
% Elapsed time is 0.002039 seconds.
tic; y = Power3(x); toc
% Elapsed time is 0.005729 seconds.
where Power3 is a C-mex:
#include "mex.h"
// Main function ===============================================================
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
size_t ndim, n;
const size_t *dims;
double *x, *y;
ndim = mxGetNumberOfDimensions(prhs[0]);
dims = mxGetDimensions(prhs[0]);
n = mxGetNumberOfElements(prhs[0]);
x = mxGetPr(prhs[0]);
plhs[0] = mxCreateUninitNumericArray(ndim, dims, mxDOUBLE_CLASS, mxREAL);
y = mxGetPr(plhs[0]);
while (n--) {
*y++ = *x * *x * *x;
x++;
}
}
This means: No, x .* x .* x is realy fast already.
  6 Comments
Ram Kishore Arumugam
Ram Kishore Arumugam on 16 Feb 2021
Hi@Walter Roberson.. this decomposition could be faster for higher powers. I just tried, for cube it is slower. Thanks for the idea!!
James Tursa
James Tursa on 16 Feb 2021
Edited: James Tursa on 16 Feb 2021
@Jan, the MATLAB times operation is multi-threaded. If you multi-thread the mex routine you could match the times performance. Seems like the mex routine could be slightly faster because an intermediate variable is avoided, but I don't see this advantage in the tests I run. The best I can do with a multi-threaded OpenMP for loop is match the x.*x.*x performance, and it looks like the memory usage is about the same. Maybe the parser is smart enough in this situation to avoid the intermediate variable also?

Sign in to comment.

More Answers (0)

Categories

Find more on Operators and Elementary Operations 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!