Generating a matrix in javascript
1 min read

Generating a matrix in javascript

When I started to learn computer programming back in middle school, the matrix and the array were among the first things that I was required to know how to handle and implement. Since then I discovered more ways to store data, some better, some not, but I still find myself oftenly in a nostalgic situation where I think a matrix might come in handy.

While Javascript offers native support for arrays, the same thing cannot be told about matrixes. Therefore, I made a little function that help you generate a javascript matrix

//generate matrix function
//parametres: l - number of lines, required
//parametres: c - number of columns, optional, in it's abscence a square matrix will be made
function matrix(l, c) {
	c = (typeof c === "undefined") ? l : c; //defaults to the number of lines, to generate the square matrix
	var mat = new Array(l);
	
	for (var i = 0; i < l; ++ i) {
		mat[i] = new Array(c);
	}
	
	return mat;
}

It's very simple to use it

var myMatrix1 = matrix(4);
//generates a 4 by 4 matrix
//0  0  0  0
//0  0  0  0
//0  0  0  0
//0  0  0  0

var myMatrix2 = matrix(2, 3);
//generates a 2 by 3 matrix
//0  0  0
//0  0  0

You can read and write any of its elements just like you would do it in any other language:

myMatrix[1][1] = 'test';
console.log(myMatrix[1][1]); 
//outputs 'test'

I hope it will be as useful for you as it was for me!

P.S. Be careful, the generated matrix is not filled with "0" values! The two matrixes in the comments are there only for a visual purpose.