UNPKG

mathjs

Version:

Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser and offers an integrated solution to work with numbers, big numbers, complex numbers, units, and matrices.

65 lines (54 loc) 1.65 kB
module.exports = function (math) { var util = require('../../util/index'), Matrix = require('../../type/Matrix'), collection = require('../../type/collection'), object = util.object, string = util.string; /** * Create the transpose of a matrix * * transpose(x) * * @param {Array | Matrix} x * @return {Array | Matrix} transpose */ math.transpose = function transpose (x) { if (arguments.length != 1) { throw new math.error.ArgumentsError('transpose', arguments.length, 1); } var size = math.size(x).valueOf(); switch (size.length) { case 0: // scalar return object.clone(x); case 1: // vector return object.clone(x); case 2: // two dimensional array var rows = size[1], cols = size[0], asMatrix = (x instanceof Matrix), data = x.valueOf(), transposed = [], transposedRow, clone = object.clone; if (rows === 0) { // whoops throw new RangeError('Cannot transpose a 2D matrix with no rows' + '(size: ' + string.format(size) + ')'); } for (var r = 0; r < rows; r++) { transposedRow = transposed[r] = []; for (var c = 0; c < cols; c++) { transposedRow[c] = clone(data[c][r]); } } return asMatrix ? new Matrix(transposed) : transposed; default: // multi dimensional array throw new RangeError('Matrix must be two dimensional ' + '(size: ' + string.format(size) + ')'); } }; };