sum.js (1697B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2020 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var Float64Array = require( '@stdlib/array/float64' ); 24 25 26 // MAIN // 27 28 /** 29 * Computes the sum along a matrix dimension. 30 * 31 * @param {Matrix} mat - input matrix 32 * @param {number} [dim=2] - matrix dimension along which to compute the sum. If `dim=1`, compute along matrix rows. If `dim=2`, compute along matrix columns. 33 * @returns {(Int32Array|number)} sums or 0 34 */ 35 function sum( mat, dim ) { 36 var out; 37 var s0; 38 var s1; 39 var s; 40 var M; 41 var N; 42 var o; 43 var i; 44 var j; 45 var k; 46 47 if ( dim === 1 ) { 48 // Compute along the rows... 49 M = mat.shape[ 1 ]; 50 N = mat.shape[ 0 ]; 51 s0 = mat.strides[ 1 ]; 52 s1 = mat.strides[ 0 ]; 53 } else { 54 // Compute along the columns... 55 M = mat.shape[ 0 ]; 56 N = mat.shape[ 1 ]; 57 s0 = mat.strides[ 0 ]; 58 s1 = mat.strides[ 1 ]; 59 } 60 if ( M === 0 || N === 0 ) { 61 return 0; 62 } 63 out = new Float64Array( M ); 64 o = mat.offset; 65 for ( i = 0; i < M; i++ ) { 66 k = o + ( i*s0 ); 67 s = 0; 68 for ( j = 0; j < N; j++ ) { 69 s += mat.data[ k + ( j*s1 ) ]; 70 } 71 out[ i ] = s; 72 } 73 return out; 74 } 75 76 77 // EXPORTS // 78 79 module.exports = sum;