Beispiel #1
0
        /// <summary>
        /// Sums two matrices.
        /// </summary>
        /// <param name="alpha">Scalar factor for (this).</param>
        /// <param name="beta">Scalar factor for (other).</param>
        /// <param name="other">The matrix added to this instance.</param>
        /// <param name="result">Contains the sum: alpha*(this) + beta*(other).</param>
        /// <remarks>
        /// The (result) matrix has to be fully initialized and provide enough space for
        /// the nonzero entries of the sum. An upper bound is the sum of the nonzeros count
        /// of (this) and (other).
        /// </remarks>
        public void Add(double alpha, double beta, CompressedColumnStorage <double> other,
                        CompressedColumnStorage <double> result)
        {
            int p, j, nz = 0;

            int m = this.nrows;
            int n = this.ncols;

            // check inputs
            if (m != other.RowCount || n != other.ColumnCount)
            {
                throw new ArgumentException(); // TODO: ex
            }

            var bi = other.ColumnPointers;
            var bx = other.Values;

            int anz = this.ColumnPointers[ncols];
            int bnz = bi[n];

            // Workspace
            var w = new int[m];
            var x = new double[m];

            // Allocate result: (anz + bnz) is an upper bound

            var ci = result.ColumnPointers;
            var cj = result.RowIndices;
            var cx = result.Values;

            for (j = 0; j < n; j++)
            {
                ci[j] = nz;                                              // column j of C starts here
                nz    = this.Scatter(j, alpha, w, x, j + 1, result, nz); // alpha*A(:,j)
                nz    = other.Scatter(j, beta, w, x, j + 1, result, nz); // beta*B(:,j)

                for (p = ci[j]; p < nz; p++)
                {
                    cx[p] = x[cj[p]];
                }
            }

            // Finalize the last column
            ci[n] = nz;

            // Remove extra space
            result.Resize(0);
            result.SortIndices();
        }