Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate and get a length of a multidimensional array / matrix?

How do i instantiate a multidimensional array / matrix in JavaScript and Typescript, and how do i get the matrix length (number of rows) and lengths of the matrix rows?

like image 417
Faris Zacina Avatar asked Sep 22 '14 13:09

Faris Zacina


People also ask

How do you find the length of a multidimensional array?

To get the length of a multidimensional (row/column) array, we can use the Array. GetLength() method in C#. Let's say you have a multidimensional array like this. Note: Dimensions are zero-based (0) indexing.

How do I find the length of a matrix?

Size of a matrix = number of rows × number of columns. It can be read as the size of a matrix and is equal to number of rows “by” number of columns.

How do you find the dimensions of a 2D matrix?

We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.


1 Answers

In Typescript you would instantiate a 2x6 Matrix / Multidimensional array using this syntax:

var matrix: number[][] = 
[
    [ -1, 1, 2, -2, -3, 0 ],
    [ 0.1, 0.5, 0, 0, 0, 0 ]
];

 //OR

var matrix: Array<number>[] =
[
    [ -1, 1, 2, -2, -3, 0 ],
    [ 0.1, 0.5, 0, 0, 0, 0 ]
];

The equivalent in JavaScript would be:

var matrix = 
[
    [ -1, 1, 2, -2, -3, 0 ],
    [ 0.1, 0.5, 0, 0, 0, 0 ]
];

The JavaScript syntax is also valid in TypeScript, since the types are optional, but the TypeScript syntax is not valid in JavaScript.

To get different lengths you would use the same syntax in JS and TS:

var matrixLength = matrix.length; // There are two dimensions, so the length is 2. This is also the column size.
var firstDimensionLength = matrix[0].length; // The first dimension row has 6 elements, so the length is 6
var secondDimensionLength = matrix[1].length; // The second dimension row has 6 elements so the length is 6
like image 151
Faris Zacina Avatar answered Sep 28 '22 21:09

Faris Zacina