Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Matrix Kotlin:矩阵中行元素求和的优雅方式?_Matrix_Kotlin_Functional Programming_Mapping_Column Sum - Fatal编程技术网

Matrix Kotlin:矩阵中行元素求和的优雅方式?

Matrix Kotlin:矩阵中行元素求和的优雅方式?,matrix,kotlin,functional-programming,mapping,column-sum,Matrix,Kotlin,Functional Programming,Mapping,Column Sum,给定(行中的)个(行)元素,除了为循环编写“”,还有没有更好的方法来获得类似(行[0][0]+行[1][0]+..行[n][0])的和列表 您可以使用和来实现这一点 以下是3种方法:(1)计算总矩阵和,(2)计算给定行的和,(3)计算给定列的和: val arr = arrayListOf( arrayListOf(1, 2, 3), arrayListOf(4, 5, 6), arrayListOf(7, 8, 9) ) fun matrixS

给定(行中的)个(行)元素,除了为循环编写“
”,还有没有更好的方法来获得类似(
行[0][0]+行[1][0]+..行[n][0]
)的和列表

您可以使用和来实现这一点

以下是3种方法:(1)计算总矩阵和,(2)计算给定行的和,(3)计算给定列的和:

val arr = arrayListOf(
        arrayListOf(1, 2, 3),
        arrayListOf(4, 5, 6),
        arrayListOf(7, 8, 9)
)

fun matrixSum() = arr.sumBy { it.sum() }
fun rowSum(row: Int) = arr[row].sum()
fun colSum(col: Int) = arr.sumBy {row -> row[col] }
// shorter alternative: fun colSum(col: Int) = arr.sumBy { it[col] }
根据您的问题,您想调用
colSum(0)
。这将提取
行[0]
(索引
0
的每行值)并对这些值求和

编辑:

关于您在评论部分提出的问题,有以下两种方法:(1)计算所有行和,作为列表返回;和(2)计算所有列和,作为列表返回

fun rowSums() = arr.map { it.sum() }
fun colSums() = arr[0].indices.map { col -> colSum(col) }
// shorter alternative:
// fun colSums() = arr[0].indices.map(::colSum)
// another version that does not call colSum:
// fun colSums() = arr[0].indices.map { col -> arr.sumBy { row -> row[col] } }

为了解释
colSums
(假设所有行的列数都相同):首先,您抓取第一行(
arr[0]
),然后获取其(即,其列数
0
1
,…,直到
nCols
),然后将这些索引添加到各自的
colSum()
结果中。这可能不是最有效的方法,但它非常可读。

好的,因此我可以得到colSum(0),如何在映射{}中使用它来接收数组作为所有列的和?我刚刚尝试了几个语法选项,但无法获得它。@ArnieSchwarzvogel我更新了我的答案以解决您的问题。最好是
arr[row]
,而不是
arr.get(row)
fun rowSums() = arr.map { it.sum() }
fun colSums() = arr[0].indices.map { col -> colSum(col) }
// shorter alternative:
// fun colSums() = arr[0].indices.map(::colSum)
// another version that does not call colSum:
// fun colSums() = arr[0].indices.map { col -> arr.sumBy { row -> row[col] } }