4
votes

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.

1
you probably need to loop on this. Plus, a 2x2 matrix loop is definetly nothing to worry about. "Early optimization is the root of all evil"!Ander Biguri
The answers to this question might be applicable to your problem. Also, you might be able to get other ideas from here. Finally, there's this FEX submission....Dev-iL
This can only be done with a loop, but it's very fast. Don't discount loops just because you were told they were in general terrible. Loops can be quite fast if you know how to use them correctly. See the post linked as the duplicate for more details.rayryeng
I'm not so much worried about speed here as I am learning alternative ways of doing operations in Matlab. I've done enough coding with for loops already and I'm trying to learn how to do things without them whether it's better or not.Kyle Turck
For this particular problem I think a for loop is best fitting, but for calculating a matrix of high powers I would say there are other ways. For example this maths stackexchange linkpatrik

1 Answers

2
votes

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