问题描述
我试图弄清楚Google App Script语言是否支持任何可以在后端使用的矩阵操作。
感谢!
Google Apps脚本是Javascript的变体 - 所以,是的,它可以支持矩阵运算,或任何其他数学运算。也就像Javascript一样,它本身不能这样做 - 你需要自己编写函数,或者找到适合的函数库。
对于矩阵运算,这里有一个选项。 Jos de Jong为Node.js提供的库可在Google Apps脚本中按原样运行。您可以阅读其对矩阵的支持。
-
复制最小化的
math.js
,并将其粘贴到,以便将该库添加到该脚本中。完成该操作后,该库可作为math
来访问,例如,math.someMethod()
-
请尝试以下示例 - 注释显示您可以在日志:
/ **
*演示mathjs数组&矩阵操作。
* /
函数matrix_demo(){
var array = [[2,0],[ - 1,3]]; // Array
var matrix = math.matrix([[7,1],[ - 2,3]]); //矩阵
//对数组和矩阵执行计算
print(math.square(array)); // Array,[[4,0],[1,9]]
print(math.square(matrix)); // Matrix,[[49,1],[4,9]]
//用混合数组和矩阵输入执行计算
print(math.add(array,matrix)) ; // Matrix,[[9,1],[-3,6]]
print(math.multiply(array,matrix)); // Matrix,[[14,2],[-13,8]]
//创建一个矩阵。函数的输出类型由
//配置选项`matrix`
print(math.ones(2,3))确定。 // Matrix,[[1,1,1],[1,1,1]]
}
/ **
*辅助函数用于输出安慰。值将被格式化。
* @param {*}值
* /
函数print(value){
var precision = 14;
Logger.log(math.format(value,precision));
}
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!
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));
}
这篇关于Google脚本中的矩阵操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!