beorn
beorn

Reputation: 45

How to create a custom function to find the determinant of 3x3 matrix

I know that det(A) is in matlab.

I want to do a function that take a matrix A(3x3) and returns the determinant. I know it's dumb but it's for understanding functions.

My attempt:

function [myDet] = myDet(a)
  myDet = a(1,1) * (a(2,2) * a(3,3) - a(3,2) * a(2,3))
        - a(1,2) * (a(2,1) * a(3,3) - a(3,1) * a(2,3))
        + a(1,3) * (a(2,1) * a(3,2) - a(3,1) * a(2,2))
endfunction

Upvotes: 1

Views: 5502

Answers (3)

Giuseppe Crinò
Giuseppe Crinò

Reputation: 546

Using GNU/Octave ...

First, semantic is probably not the one you meant. It is

function [ <output> ] = <function_identifier> ( <input> )

Hence

function [ d ] = myDet ( A )

Then, apparently multiple line statements fails to be evaluated as a single instruction. I solved this way

function [ d ] = myDet ( A )

    ## If A is a 3x3 matrix, compute the determinant as follows ... 
    if size(A) == [3,3]
        d = A(1,1) * (A(2,2) * A(3,3) - A(3,2) * A(2,3)) + \
            - A(1,2) * (A(2,1) * A(3,3) - A(3,1) * A(2,3)) + \
            + A(1,3) * (A(2,1) * A(3,2) - A(3,1) * A(2,2));
    ## ... else, use the default function ...
    else
        d = det(A)
    endif
end

Note

I've changed the name of your output variable (from myDet to d) since in general is not good practice calling the output of a function as the name you give the procedure. In Octave (ehm ...Matlab) this sounds to have no consequences, but remind there are some programming languages where you can directly handle functions by their identifier (I'm thinking of Javascript, for instance).

Upvotes: 2

mvw
mvw

Reputation: 5105

Try

function [y] = myDet(A)
      y = A(1,1) * (A(2,2) * A(3,3) - A(3,2) * A(2,3)) \
        - A(1,2) * (A(2,1) * A(3,3) - A(3,1) * A(2,3)) \
        + A(1,3) * (A(2,1) * A(3,2) - A(3,1) * A(2,2));
end

Upvotes: 0

hiddeninthewifi
hiddeninthewifi

Reputation: 47

I don't have MATLAB close at hand, but I think you'll need a space in 'end function'. Other than that, it looks good. I'd put in some error checking that size(a) = 3 3. (Actually, you don't really need 'end' at all if it's in its own file. And it's 'end', not 'end function'). The return value should be just 'myDet'

function out = myDet(a)
out = a(1,1) * (a(2,2) * a(3,3) - a(3,2) * a(2,3))
  - a(1,2) * (a(2,1) * a(3,3) - a(3,1) * a(2,3))
  + a(1,3) * (a(2,1) * a(3,2) - a(3,1) * a(2,2))
end

Changed output variable to 'out' so that you don't have a method and variable by the same name. That can get hairy.

Upvotes: 0

Related Questions