Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

matlab - Powers of a matrix

I have a square matrix A (nxn). I would like to create a series of k powers of this matrix into an nxnxk multidimensional matrix (Not element-wise but actual powers of the matrix), i.e.getting [A^0 A^1 A^2..A^k]. It's sort of a varied vandermonde for matrix case.

I am able to do it with loops but it is annoying and slow. I tried using bsxfun but no luck since I am probably missing something here.

Here is a simple loop that I did:

for j=1:1:100 
    final(:,:,j)=A^(j-1); 
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are trying to perform cummulative version of mpower with a vector of k values.

Sadly, bsxfun hasn't evolved yet to handle such a case. So, the best I could suggest at this point would be having a running storage that accumulates the matrix-product at each iteration to be used at the next one.

Your original loop code looked something like this -

final = zeros([size(A),100]);
for j=1:1:100 
    final(:,:,j)=A^(j-1); 
end

So, with the suggestion, the modified loopy code would be -

final = zeros([size(A),100]);
matprod = A^0;
final(:,:,1) = matprod;
for j=2:1:100 
    matprod = A*matprod;
    final(:,:,j)= matprod;
end

Benchmarking -

%// Input
A = randi(9,200,200);

disp('---------- Original loop code -----------------')
tic
final = zeros([size(A),100]);
for j=1:1:100 
    final(:,:,j)=A^(j-1); 
end
toc

disp('---------- Modified loop code -----------------')
tic
final2 = zeros([size(A),100]);
matprod = A^0;
final2(:,:,1) = matprod;
for j=2:1:100 
    matprod = A*matprod;
    final2(:,:,j)= matprod;
end
toc

Runtimes -

---------- Original loop code -----------------
Elapsed time is 1.255266 seconds.
---------- Modified loop code -----------------
Elapsed time is 0.205227 seconds.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...