Laimond
Laimond

Reputation: 199

Creating array from raising matrix to power in matlab

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

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 can I do if A is a matrix?

Upvotes: 5

Views: 1043

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112669

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

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

This gives you a 3D array as result (2x3x10 in this case).


If exponents are consecutive values, the following code may be faster:

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

Upvotes: 3

Rash
Rash

Reputation: 4336

Try like this,

 % 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);

Upvotes: 2

Related Questions