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.
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].
The transpose of the matrix is calculated by simply swapping columns to rows: transpose[j][i] = matrix[i][j];
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))].
In functional programming languages, the usual approach for matrix transposition is to use unzip
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With