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?
To create a matrix that has multiple rows, separate the rows with semicolons. To create an evenly spaced array, specify the start and end point by using the ':' operator. Another way to create a matrix is to use a function, such as ones, zeros or rand.
Matrices and arrays are the fundamental representation of information and data in MATLAB. To create an array with multiple elements in a single row, separate the elements with either a comma ',' or a space. This type of array is called a row vector.
Multidimensional arrays in MATLAB are an extension of the normal two-dimensional matrix. Generally to generate a multidimensional array, we first create a two-dimensional array and extend it. For example, let's create a two-dimensional array a.
This type of array is called a column vector. To create a matrix that has multiple rows, separate the rows with semicolons. To create an evenly spaced array, specify the start and end point by using the ':' operator. Another way to create a matrix is to use a function, such as ones, zeros or rand.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With