0
votes

I am new to Matlab and this might seem very easy.

I have 2 matrices:

a = [1 1 1; 2 2 2 ; 3 3 3 ; 4 4 4 ; 5 5 5];
b = [4 4 4; 3 2 4 ; 1 5 7 ; 4 3 8 ; 2 4 7];

I wanted to calculate the determinant of each row of the two matrices added by a row of ones (a 3*3 matrix), and put all the determinants in another array. For example, first determinant (d(1)) would be from this matrix:

1 1 1
4 4 4
1 1 1

and the second one (d(2)) would be from this matrix:

2 2 2
3 2 4
1 1 1

and so on...

When I try this:

m = size(a,1);
ons = ones(m,3);
d = det([a(:,:) ; b(:,:) ; ons(:,:)]);

I get this error:

Error using det

Matrix must be square.

How can I calculate all the determinants at once without using loop?

1
What do you mean by "the determinant of each row"? The determinant is only defined for square matrices, and built-ins will only compute it one matrix at a time.Andras Deak
do you understand the error you got ?bla
The determinant of A, a transformation matrix Rm -> Rm, calculate the ratio between the surface (in 2D or hypersurface in mD) obtained if we apply those transformation matrix to some surface (in 2D or hypersurface in mD) and the original surface. So it does not make any sens to compute the determinant of a non square matrix because we would compute, for example, the ratio between a volume and a surface and obtain infinity as a result.obchardon
OK, so I agree you have matrices. As far as I can tell built-in det will only compute one determinant at a time. However, if your matrices are always 3x3, you can hand-code the determinant (it has 6 terms), which you can do in a vectorized way, if you prefer.Andras Deak
@AndrasDeak Yes they are always 3x3. I will try to do it in a vectorized way using the six terms. For the first term for example, it should be: a(:,1) * b(:,2) * 1.Hadi GhahremanNezhad

1 Answers

0
votes

Based on @Andras's suggestion, I tried the determinant according to wiki page:

fgdg

Based on @beaker's suggestion, this works:

d = (a(:, 1) .* b(:, 2) - a(:, 2) .* b(:, 1)) - (a(:, 1) .* b(:, 3) - a(:, 3) .* b(:, 1)) + (a(:, 2) .* b(:, 3) - a(:, 3) .* b(:, 2))

These are slower alternatives:

d = arrayfun(@(x)det([a(x,:);b(x,:);ones(1,3)]),1:length(a));
d = bsxfun(@times, a(:,1), b(:,2))+ bsxfun(@times, a(:,2), b(:,3)) +...
    bsxfun(@times, a(:,3), b(:,1))- bsxfun(@times, a(:,3), b(:,2)) -...
    bsxfun(@times, a(:,2), b(:,1))- bsxfun(@times, a(:,1), b(:,3));