Computing determinants of a 3D array
Mostrar comentarios más antiguos
Let’s say I have an NxNxL array. L is typically 10^4-10^5, and N is typically 10^0-10^1.
My goal is to calculate a vector of length L, where the i-th cell contains the determinant of (:,:,i).
I currently use for-loop, as det(A) accepts 3D arrays with the last dimension being a singleton, so this code works:
for i = 1:L
Vec(i) = det(Mat(:,:,i));
end
However, it seems weird that i can't implement this in a vectorial fasion. Can anybody think of any way to get rid of the for loop? Note that the format of an 3D array is pretty stiff, i.e. i can't change the input to cell array and use cellfun.
Thanks!
Yanir.
2 comentarios
Matt J
el 26 de Nov. de 2012
Hopefully, the reason you're asking for this is not for the purpose of solving many linear systems.
Yanir Hainick
el 29 de Nov. de 2012
Respuesta aceptada
Más respuestas (2)
For small N, it would be an advantage to vectorize the determinant formula explicitly (example for for N=2 below). For larger N, maybe you could do the same thing recursively.
%fake data
N=2;
L=1e5;
Mat=rand(N,N,L);
tic
Vec=zeros(1,L);
for ii=1:L
Vec(ii)=det(Mat(:,:,ii));
end
toc;
%Elapsed time is 0.194555 seconds.
Mat=reshape(Mat,[],L);
tic;
Vec =Mat(1,:).*Mat(4,:) - Mat(2,:).*Mat(3,:);
toc
%Elapsed time is 0.000378 seconds.
2 comentarios
Pi Ting
el 8 de Nov. de 2017
The line
Vec =Mat(1,:).*Mat(3,:) - Mat(2,:).*Mat(4,:);
should be
Vec =Mat(1,:).*Mat(4,:) - Mat(2,:).*Mat(3,:)?
Al in St. Louis
el 8 de Abr. de 2020
I had to use Pi Ting's expression to get the correct answers. This is exactly what I need to do!
Yanir Hainick
el 29 de Nov. de 2012
0 votos
Categorías
Más información sobre Startup and Shutdown en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!