问题
I'm trying to figure out if Google App Script language supports any sort of matrix operations that can be used on the back end.
Thanks!
回答1:
Google Apps Script is a variant of Javascript - so, yes, it can support matrix operations, or any other math you want to do. Also like Javascript, it cannot do so natively - you need to write the functions yourself, or find a library that suits.
For matrix operations in particular, here's an option. Jos de Jong's mathjs library for Node.js works as-is in Google Apps Script. You can read up on its support for matrices here.
Copy the minimized
math.js
source from github, and paste it into a new script file in the script that you want to add the library to. With that done, the library is accessible asmath
, e.g.math.someMethod()
Try the following example - the comments show what you can expect in the logs:
/**
* Demonstrate mathjs array & matrix operations.
*/
function matrix_demo() {
var array = [[2, 0],[-1, 3]]; // Array
var matrix = math.matrix([[7, 1],[-2, 3]]); // Matrix
// perform a calculation on an array and matrix
print( math.square(array) ); // Array, [[4, 0], [1, 9]]
print( math.square(matrix) ); // Matrix, [[49, 1], [4, 9]]
// perform calculations with mixed array and matrix input
print( math.add(array, matrix) ); // Matrix, [[9, 1], [-3, 6]]
print( math.multiply(array, matrix) ); // Matrix, [[14, 2], [-13, 8]]
// create a matrix. Type of output of function ones is determined by the
// configuration option `matrix`
print( math.ones(2, 3) ); // Matrix, [[1, 1, 1], [1, 1, 1]]
}
/**
* Helper function to output a value in the console. Value will be formatted.
* @param {*} value
*/
function print (value) {
var precision = 14;
Logger.log(math.format(value, precision));
}
来源:https://stackoverflow.com/questions/25560969/matrix-operations-in-google-script