MATLAB: Is there a faster way to cube a array

arrayoperation

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,

Best Answer

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.