Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 362
Laimond Avatar asked Oct 25 '14 14:10

Laimond


People also ask

How do you create a matrix in MATLAB?

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.

What are matrices and arrays in MATLAB?

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.

How to create multidimensional arrays in MATLAB?

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.

How do you create a column vector in MATLAB?

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.


2 Answers

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);
like image 163
Luis Mendo Avatar answered Oct 09 '22 09:10

Luis Mendo


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);
like image 26
Rashid Avatar answered Oct 09 '22 07:10

Rashid