矩阵运算序言

0 matrix prolog

嗨,我需要一些 prolog 功能的帮助,请:

定义谓词:

row(X,N,C):C 是矩阵 X 的第 N 行。

column(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
Run Code Online (Sandbox Code Playgroud)

小智 5

考虑:

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).
Run Code Online (Sandbox Code Playgroud)

测试:

matrix([[a,b,c],[d,e,f],[g,h,i]]).
Run Code Online (Sandbox Code Playgroud)

对于行:

 ?- 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.
Run Code Online (Sandbox Code Playgroud)

列:

?- 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.
Run Code Online (Sandbox Code Playgroud)

第一栏:

?- 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]].
Run Code Online (Sandbox Code Playgroud)

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

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

?- symmetrical([[a,b,c],[b,d,e],[c,e,f]]).
true.
Run Code Online (Sandbox Code Playgroud)