Using mtimesx-function multiple times without a loop-function
1 view (last 30 days)
Show older comments
Edit: each slice of matrix P is of tridiagonal form.
Hi,
I need to compute the m-th power of every single 2D-layer of a 3D matrix P with size(P)=[50,50,1000] in an efficient/fast way.
I tried using mtimesx, like
if true
P_s=P;
for i=1:m
P_s=mtimesx(P_s,P_s);
end
end
However it takes too much time, since m is in the order of 1e5. Is there are way to implement m>2 without using a loop-function?
I'm glad for any advice, thanks
markus
2 Comments
Answers (1)
Matt J
on 5 Oct 2012
Edited: Matt J
on 5 Oct 2012
Don't know what kind of speed you're looking for but this doesn't seem too bad. It works by converting P to a block diagonal sparse matrix whose blocks are the slices of the original P,
P=rand(50,50,1000); m=1e5;
Pcell=num2cell(P,[1,2]);
Pcell=cellfun(@(c) sparse(c), Pcell,'uni',0);
P_s=blkdiag(Pcell{:});
tic;
P_s=P_s^m;
toc;
%Elapsed time is 6.253806 seconds.
I leave it to you to convert P_s back to a 3D stack if that's what you need.
4 Comments
James Tursa
on 5 Oct 2012
@Jan: Probably not. For reasonably low powers it can outperform the built-in mpower function for speed. So if you are doing a low power calculation many times (e.g. in a loop) it can be useful. But for higher powers it will eventually suffer from accuracy loss just like any other repeated-matrix-multiply method. So I would still opt for calling mpower in a loop or use the sparse approach ala Matt J for higher powers.
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!