Kyle Turck
Kyle Turck

Reputation: 53

How to raise a matrix to a vector of powers in matlab without for loop?

I have a 2x2 matrix that I want to multiply by itself 10 times while storing the result after each multiplication. This can easily be done with a for loop but I would like to vectorize it an eliminate the for loop. My approach was to have my 2x2 matrix a and raise it to a vector b with elements 1:10. The answer should be a 2x2x10 matrix that replicates typing

a^b(1)
a^b(2)
.
.
.
a^b(10)

To clarify I'm not doing this element wise I need actual matrix multiplication, and prefer not to use a for loop. Thanks for any help you can give me.

Upvotes: 4

Views: 1302

Answers (1)

Hammer. Wang
Hammer. Wang

Reputation: 714

here is the code for you. I use the cellfun to do this and I have comments after each line of the code. It can compute and store from fisrt - nth order of the self-multiplication of an arbitrary matrix m. If you have any question, feel free to ask.

function m_powerCell = power_store(m, n) %m is your input matrix, n is the highest power you want to reach

  n_mat = [1:n]; %set a vector for indexing each power result in cell

  n_cell = mat2cell(n_mat,1,ones(1,n)); %set a cell for each of the power

  m_powerCell = cellfun(@(x)power(m, x), n_cell, 'uni', 0);  %compute the power of the matrix

end

%this code will return a cell to you, each element is a matrix, you can
%read each of the matrix by m_powerCell{x}, x represents the xth order 

Upvotes: 3

Related Questions