Is there a faster way to cube a array?

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

B = A.^3 ;
But looks what you have tried takes less time..
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

Hi Jan. Thanks for the detailed explanation.!! The array size might go up in some simulations, that is why I wanted to check if there are any alternatives.
If the power were going up instead of the array size, then we would have something to work with, as there are ways to decompose positive integer powers for efficiency. But it doesn't help for power 3.
@Walter Roberson Unfortunately, only the size of the array increases up to 20times, which would proportionally increase the time. thanks :)
If you happen to also be doing A.^2 in the same function then you can save by
A2 = A.*A;
A3 = A2.*A;
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!