Creating an array from matrix enhancement to power in Matlab

I need to create a 3-dimensional array from lifting all the elements of the matrix to different power given by the vector. Is there a way to avoid a power cycle?

For example, if A is a scalar, I could do

A = 2;
b = 1:10;
C = A.^b;

If A is a vector, I could do

A = [1, 2, 3];
b = 1:10;
C = bsxfun(@power, A, (0:5)');

What if A is a matrix?

+4
source share
2 answers

Use again bsxfun, but position the exponents ( b) in the third dimension:

A = [1, 2 3; 4 5 6];
b = 1:10;
C = bsxfun(@power, A, permute(b(:), [2 3 1]));

As a result, you get a 3D array (in this case 2x3x10).


If the metrics are sequential values, the following code may be faster:

n = 10; %// compute powers with exponents 1, 2, ..., n
C = cumprod(repmat(A, [1 1 n]) ,3);
+3
source

Try it,

 % m & n being the dimensions of matrix A
 A = randi(9,[m n]);
 P = cat(3,1*ones(m,n),2*ones(m,n),3*ones(m,n));
 C = bsxfun(@power, A, P);
+1
source

All Articles