Returning Defining Vector - Matlab

I have a matrix with three sizes Y (i, j, w). I want to get the determinant vector d (w), in which each number will be the determinant of the matrix Y (:,:, ).

Is there an elegant syntax for it, or do I just need to use a loop?

thank

+5
source share
2 answers

Well, first of all, you actually NEVER want to calculate the determinants, you just think that it is. In fact, this is almost never good, because determinants scale so poorly. Too often they are used to deduce the state of the singularity of the matrix, which is very difficult to do from the point of view of numerical analysis.

Outlining my mini pomp against determinants in general ...

OPTION 1:

3- , . mat2cell .

, cellfun . cellfun (@det) , . ? , det , , .

2:

, , , 2x2 3x3, . , , , 2x2, Y 2x2xn:

d = Y(1,1,:).*Y(2,2,:) - Y(1,2,:).*Y(2,1,:);

, , 2x2 Y. 3x3 , , . 3x3- , .

d = Y(1,1,:).*Y(2,2,:).*Y(3,3,:) + ...
    Y(2,1,:).*Y(3,2,:).*Y(1,3,:) + ...
    Y(3,1,:).*Y(1,2,:).*Y(2,3,:) - ...
    Y(3,1,:).*Y(2,2,:).*Y(1,3,:) - ...
    Y(2,1,:).*Y(1,2,:).*Y(3,3,:) - ...
    Y(1,1,:).*Y(3,2,:).*Y(2,3,:);

, OPTION 2 , .

: , . , 1e5-.

p = 2;
n = 1e5;
Y = rand(p,p,n);

tic,
d0 = squeeze(Y(1,1,:).*Y(2,2,:) - Y(2,1,:).*Y(1,2,:));
toc

Elapsed time is 0.002141 seconds.

tic,
X = squeeze(mat2cell(Y,p,p,ones(1,n)));
d1= cellfun(@det,X);
toc

Elapsed time is 12.041883 seconds.

.

std(d0-d1)
ans =
   3.8312e-17

, , , . , MANY , 2x2 3x3. 44 . , , , .

, MATLAB det LU, . , , 2x2 3x3 - . ( , , .)

+7

arrayfun:

d = arrayfun(@(w) det(Y(:, :, w)), 1 : size(Y, 3));

: :

p = 10;
n = 1e4;
Y = rand(p,p,n);

1:

>> tic, d1 = arrayfun(@(w) det(Y(:, :, w)), 1 : size(Y, 3)); toc
Elapsed time is 0.139030 seconds.

2 ( ):

>> tic, X = squeeze(mat2cell(Y,p,p,ones(1,n))); d2= cellfun(@det,X); toc
Elapsed time is 1.318396 seconds.

3 ( ):

>> p = 10;
>> n = 1e4;
>> Y = rand(p,p,n);
>> tic; d = nan(n, 1); for w = 1 : length(d), d(w) = det(Y(:, :, w)); end; toc
Elapsed time is 0.069279 seconds.

Conclusion: the naive approach is the fastest.

+3
source

All Articles