Caroline Cruz
Caroline Cruz

Reputation: 9

Inverse matrix in prolog

    transpose([A|As], At) :-
       transpose(A, [A|As], At).

    transpose([], _, []).
    transpose([_|As], Rest, [At|Ats]) :-
       first_column(Rest, At, NewRest),
       transpose(As, NewRest, Ats).

    first_column([], [], []).
    first_column([[A|As]|Ass], [A|Acc], [As|Rest]) :-
       first_column(Ass, Acc, Rest).

Here is a function that returns the transposed matrix. How can I write a function that gives me the inverse matrix?

Upvotes: 0

Views: 557

Answers (1)

Daniel Lyons
Daniel Lyons

Reputation: 22803

To do this in the general case kind of sucks, and there are lots of algorithms to choose from.

However, the 2x2 case is very simple:

invert([[A,B],[C,D]], [[IA,IB],[IC,ID]]) :-
    Det is A*D-B*C,
    Det \= 0,
    IDet is 1/Det,
    IA is IDet*D, IB is IDet*(-B),
    IC is IDet*(-C), ID is IDet*A.

The Det \= 0 test is important, because not every matrix has an inverse.

Upvotes: 1

Related Questions