Languages
[Edit]
EN

JavaScript - transpose matrix

3 points
Created by:
Nathanial-Donald
314

In this short article we would like to show how to transpose matrix in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

function transposeMatrix(matrix) {
	var result = new Array(matrix.length);
	for (var i = 0; i < matrix.length; ++i) {
		result[i] = new Array(matrix[0].length);
	}
	for (var i = 0; i < matrix.length; ++i) {
		for (var j = 0; j < matrix[0].length; ++j) {
			result[j][i] = matrix[i][j];
		}
	}
	return result;
}

// Helper methods:

function printMatrix(matrix) {
	var text = '';
	for (var i = 0; i < matrix.length; ++i) {
		var row = matrix[i];
		for (var j = 0; j < row.length; ++j) {
			text += row[j] + ' ';
		}
		text += '\n';
	}
	console.log(text);
}

// Usage example:

var matrix = [
	[1, 2, 3],
	[4, 5, 6],
	[7, 8, 9]
];
var transposedMatrix = transposeMatrix(matrix);

printMatrix(transposedMatrix); // 1 4 7 
                               // 2 5 8 
                               // 3 6 9 

Note: above example do not check sizes of arrays.

Matrix transposition with sizes checking example

Solution presented in this section checks each row size and inform if transposition can not be done.

// ONLINE-RUNNER:browser;

function createMatrix(width, height) {
	var result = new Array(height);
	for (var i = 0; i < height; ++i) {
		result[i] = new Array(width);
	}
	return result;
} 

function transposeMatrix(matrix) {
	if (matrix.length == 0) {
		return [];
	}
	var matrixRow = matrix[0];
	if (matrixRow == null) {
		throw new Error('Undefined matrix row 1.');
	}
	var matrixWidth = matrixRow.length;
	var matrixHeight = matrix.length;
	var result = createMatrix(matrixWidth, matrixHeight);
	for (var i = 0; i < matrixHeight; ++i) {
		var matrixRow = matrix[i];
      	if (matrixRow == null) {
			throw new Error('Undefined matrix row ' + (i + 1) + '.');
		}
		if (matrixWidth != matrixRow.length) {
			throw new Error('Matrix row ' + (i + 1) + ' has different width than row 1.');
		}
		for (var j = 0; j < matrixWidth; ++j) {
			result[j][i] = matrixRow[j];
		}
	}
	return result;
}

// Helper methods:

function printMatrix(matrix) {
	var text = '';
	for (var i = 0; i < matrix.length; ++i) {
		var row = matrix[i];
		for (var j = 0; j < row.length; ++j) {
			text += row[j] + ' ';
		}
		text += '\n';
	}
	console.log(text);
}

// Usage example:

var matrix = [
	[1, 2, 3],
	[4, 5, 6],
	[7, 8, 9]
];
var transposedMatrix = transposeMatrix(matrix);

printMatrix(transposedMatrix); // 1 4 7 
                               // 2 5 8 
                               // 3 6 9 

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join