Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing a 2 dimensional matrix in Erlang

Given a matrix like below, transform it, say, 90 degrees into the second matrix below. How would you go about doing this in the cleanest way possible? Short/succinct/clear solutions where the point is easy to grasp is preferred.

From

[[A1,A2,A3],
 [B1,B2,B3],
 [C1,C2,C3]]

To

[[A1,B1,C1],
 [A2,B2,C2],
 [A3,B3,C3]]

Edit: I realize it was not clear from original question. I'd like to know how to do this in Erlang.

like image 522
Magnus Kronqvist Avatar asked Mar 22 '11 09:03

Magnus Kronqvist


People also ask

How do you transpose a 2d matrix?

Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[N][M] is obtained by changing A[i][j] to A[j][i].

How do you transpose a rectangular matrix in Java?

The transpose of the matrix is calculated by simply swapping columns to rows: transpose[j][i] = matrix[i][j];


2 Answers

Simplifying the solutions already given, you can do it in as short as:

-module(transp).

-export([transpose/1]).

transpose([[]|_]) -> [];
transpose(M) ->
  [lists:map(fun hd/1, M) | transpose(lists:map(fun tl/1, M))].
like image 196
Kiscsirke Avatar answered Sep 22 '22 10:09

Kiscsirke


In functional programming languages, the usual approach for matrix transposition is to use unzip.

like image 39
Michael J. Barber Avatar answered Sep 22 '22 10:09

Michael J. Barber