Powers of a matrix

丶灬走出姿态 提交于 2019-11-26 21:58:18

问题


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

回答1:


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.


来源:https://stackoverflow.com/questions/32547973/powers-of-a-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!