diff --git a/arrays.scad b/arrays.scad index 56557f6..8c8d91c 100644 --- a/arrays.scad +++ b/arrays.scad @@ -477,4 +477,29 @@ function array_dim(v, depth=undef) = +// Function: transpose() +// Description: Returns the transposition of the given array. +// Example: +// arr = [ +// ["a", "b", "c"], +// ["d", "e", "f"], +// ["g", "h", "i"] +// ]; +// t = transpose(arr); +// // Returns: +// // [ +// // ["a", "d", "g"], +// // ["b", "e", "h"], +// // ["c", "f", "i"], +// // ] +// Example: +// transpose([3,4,5]); // Returns: [[3],[4],[5]] +function transpose(arr) = + arr==[]? [] : + is_list(arr[0])? [for (i=[0:len(arr[0])-1]) [for (j=[0:len(arr)-1]) arr[j][i]]] : + [for (x=arr) [x]]; + + + + // vim: noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap diff --git a/matrices.scad b/matrices.scad index b15467e..f2ce3e8 100644 --- a/matrices.scad +++ b/matrices.scad @@ -17,27 +17,6 @@ function ident(n) = [for (i = [0:n-1]) [for (j = [0:n-1]) (i==j)?1:0]]; -// Function: matrix_transpose() -// Description: Returns the transposition of the given matrix. -// Example: -// m = [ -// [11,12,13,14], -// [21,22,23,24], -// [31,32,33,34], -// [41,42,43,44] -// ]; -// tm = matrix_transpose(m); -// // Returns: -// // [ -// // [11,21,31,41], -// // [12,22,32,42], -// // [13,23,33,43], -// // [14,24,34,44] -// // ] -function matrix_transpose(m) = [for (i=[0:len(m[0])-1]) [for (j=[0:len(m)-1]) m[j][i]]]; - - - // Function: mat3_to_mat4() // Description: Takes a 3x3 matrix and returns its 4x4 affine equivalent. function mat3_to_mat4(m) = concat( diff --git a/tests/test_arrays.scad b/tests/test_arrays.scad index e386209..f305651 100644 --- a/tests/test_arrays.scad +++ b/tests/test_arrays.scad @@ -212,4 +212,13 @@ module test_array_dim() { test_array_dim(); +module test_transpose() { + assert(transpose([[1,2,3],[4,5,6],[7,8,9]]) == [[1,4,7],[2,5,8],[3,6,9]]); + assert(transpose([[1,2,3],[4,5,6]]) == [[1,4],[2,5],[3,6]]); + assert(transpose([3,4,5]) == [[3],[4],[5]]); +} +test_transpose(); + + + // vim: noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap