Google Apps Script: take some rows or submatrix in a matrix?

Viewed 52

I have a simple question:

If i take a range of values in google apps script:

//For Example
  var matrix=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("A1:D4").getValues();

matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]];

Is it possible to get some rows or submatrix like in Matlab Notation? Something like this:

var submatrix= matrix[1:3]; //to take last three rows: submatrix = [[5,6,7,8],[9,10,11,12],[13,14,15,16]];
// or
var submatrix= matrix[1:2][1:2]; //to take: submatrix = [[6,7],[10,11]];`

I can't find a similar notation. It's frustrating to use concat and similar functions or acting previously on the range. Do you know a simplier way to work with matrix and submatix quickly?

Thank you in Advance.

1 Answers

How about the following sample script?

Pattern 1:

Use slice.

var matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];

var submatrix1 = matrix.slice(1, 4);
console.log(submatrix1) // [ [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]

var submatrix2 = matrix.slice(1, 3).map(e => e.slice(1, 3));
console.log(submatrix2) // [ [ 6, 7 ], [ 10, 11 ] ]

  • In this case, matrix is non-destructive.

Pattern 2:

Use splice.

var matrix1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];
var submatrix1 = matrix1.splice(1, 3);
console.log(submatrix1) // [ [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]

var matrix2 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]];
var submatrix2 = matrix2.splice(1, 2).map(e => e.splice(1, 2));
console.log(submatrix2) // [ [ 6, 7 ], [ 10, 11 ] ]

  • In this case, matrix is destructive.
  • In this case, at Google Apps Script, when the array length of matrix is large, when splice is used, the memory can be efficiently used than that of slice.

References:

Related