Reputation: 199
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
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
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