继续我的教堂冒险......
我有一个矩阵 A。
var idx = {1..n};
var adom = {idx, idx};
var A: [adom] int;
//populate A;
var rowsums: [idx] int;
填充行和的最有效方法是什么?
最佳答案
最有效 的解决方案很难定义。但是,这是一种计算 rowsums
的方法,它既并行又优雅:
config const n = 8; // "naked" n would cause compilation to fail
const indices = 1..n; // tio.chpl:1: error: 'n' undeclared (first use this function)
const adom = {indices, indices};
var A: [adom] int;
// Populate A
[(i,j) in adom] A[i, j] = i*j;
var rowsums: [indices] int;
forall i in indices {
rowsums[i] = + reduce(A[i, ..]);
}
writeln(rowsums);
这是利用 + reduction在 array slices的 A
。
请注意,forall
和+ reduce
都为上面的程序引入了并行性。如果 indices
的大小足够小,则仅使用 for
循环可能会更有效,从而避免产生任务。
关于chapel - 在 Chapel 中计算矩阵的 rowSums,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45724161/