sathariel
sathariel

Reputation: 19

how to transpose multidimensional (3D) matrix in prolog

I want to transpose matrix in Prolog. I'm new in Prolog and so far I know how to do it for two dimensional matrix

transpose([], []).
transpose([H|T], Ts) :- transpose(H, [H|T], Ts).

transpose([], _, []).
transpose([_|T1], L, [H1|T2]) :- lfr(L, H1, M), transpose(T1, M, T2).

lfr([], [], []).
lfr([[H3|T4]|R], [H3|T5], [T4|O]) :- lfr(R, T5, O).

but not for more. I can't find anything on google so any tips or hints will be appreciated. example:

input [ [ [1,2,3],[4,5,6] ], [ [7,8,9],[10,11,12] ] ].

output [ [ [1,4],[7,10] ], [ [2,5],[8,11] ], [ [3,6],[9,12] ] ].

Thank you.

Upvotes: 0

Views: 163

Answers (1)

lurker
lurker

Reputation: 58324

If you have a transpose predicate for a 2D matrix, then transposition of a 3D matrix can be done in the following steps:

  1. Transpose each 2D matrix element of your 3D matrix (you can use maplist/2 for this)
  2. Transpose the resulting 3D matrix as a 2D matrix of lists.

In Prolog:

matrix_3d_transposed(Matrix, TransMatrix) :-
    maplist(matrix_2d_transposed, Matrix, TMatrices),
    matrix_2d_transposed(TMatrices, TransMatrix).

Upvotes: 1

Related Questions