矩阵运算Prolog

时间:2011-04-27 16:33:36

标签: matrix prolog

嗨,我需要一些prolog函数的帮助,请:

定义谓词:

行(X,N,C):C是矩阵X的行N.

列(X,N,C):C是矩阵X的列N.

first_column(X,C,R):矩阵X由第一列C和矩阵R的其余部分组成。

对称(X):X是与对角线对称的二次矩阵。

矩阵是列表的列表:[[a,b,c],[d,e,f],[g,h,i]]>>>

          a b c
          d e f
          g h i

3 个答案:

答案 0 :(得分:4)

考虑:

row(M, N, Row) :-
    nth1(N, M, Row).

column(M, N, Col) :-
    transpose(M, MT),
    row(MT, N, Col).

symmetrical(M) :-
    transpose(M, M).

transpose([[]|_], []) :- !.
transpose([[I|Is]|Rs], [Col|MT]) :-
    first_column([[I|Is]|Rs], Col, [Is|NRs]),
    transpose([Is|NRs], MT).

first_column([], [], []).
first_column([[]|_], [], []).
first_column([[I|Is]|Rs], [I|Col], [Is|Rest]) :-
    first_column(Rs, Col, Rest).

测试:

matrix([[a,b,c],[d,e,f],[g,h,i]]).

对于行:

 ?- matrix(M), row(M, N, Row).
M = [[a, b, c], [d, e, f], [g, h, i]],
N = 1,
Row = [a, b, c] ;
M = [[a, b, c], [d, e, f], [g, h, i]],
N = 2,
Row = [d, e, f] ;
M = [[a, b, c], [d, e, f], [g, h, i]],
N = 3,
Row = [g, h, i] ;
false.

列:

?- matrix(M), column(M, N, Col).
M = [[a, b, c], [d, e, f], [g, h, i]],
N = 1,
Col = [a, d, g] ;
M = [[a, b, c], [d, e, f], [g, h, i]],
N = 2,
Col = [b, e, h] ;
M = [[a, b, c], [d, e, f], [g, h, i]],
N = 3,
Col = [c, f, i] ;
false.

第一栏:

?- matrix(M), first_column(M, C, R).
M = [[a, b, c], [d, e, f], [g, h, i]],
C = [a, d, g],
R = [[b, c], [e, f], [h, i]].

最后,矩阵对称性由任何矩阵定义,该矩阵是其自身的转置。

 ?- matrix(M), symmetrical(M).
false.

?- symmetrical([[a,b,c],[b,d,e],[c,e,f]]).
true.

答案 1 :(得分:1)

在SWI-Prolog中,您可以像这样定义行和列谓词:

row(N, Matrix, Row) :-
    nth1(N, Matrix, Row).

col(N, Matrix, Col) :-
    maplist(nth1(N), Matrix, Col).

请注意,使用这些定义,如果只给出Matrix,您也可以生成行/列,例如

?- col(N, [[a, b], [c, d]], Col).
N = 1,
Col = [a, c] ;
N = 2,
Col = [b, d] ;
false.

可以像这样生成对称矩阵:

% Generates matrix elements
element(RowN-ColN, Matrix, El) :-
    row(RowN, Matrix, Row),
    nth1(ColN, Row, El).

% Generates matrix symmetric elements, i.e. where Aij = Aji.
symmetric_element(Matrix, RowN-ColN) :-
    element(RowN-ColN, Matrix, El),
    element(ColN-RowN, Matrix, El).

% Generates row-colum indices for the upper triangle.
get_index_pair(N, RowN-ColN) :-
    between(1, N, RowN),
    succ(RowN, RowN1),
    between(RowN1, N, ColN).

% Generates matrixes where every element is symmetric.
symmetric(Matrix) :-
    length(Matrix, N),
    findall(IndexPair, get_index_pair(N, IndexPair), IndexPairs),
    maplist(symmetric_element(Matrix), IndexPairs).

用法:

?- Matrix = [[a, b, c], Row2, Row3], symmetric(Matrix), numbervars(Matrix, 0, _).
Matrix = [[a, b, c], [b, A, B|C], [c, B|D]],
Row2 = [b, A, B|C],
Row3 = [c, B|D].

答案 2 :(得分:0)


row(N,Matrix,Row) :-
        nth1(N,Matrix,Row).

col(N,Matrix,Col) :-
        findall(E,(append(_,[Row|_],Matrix),nth1(N,Row,E)),Col).