Example #1
0
        /// <summary>
        /// Replaces all cell values of the receiver with the values of another matrix.
        /// Both matrices must have the same number of rows and columns.
        /// If both matrices share the same cells (as is the case if they are views derived from the same matrix) and intersect in an ambiguous way, then replaces <i>as if</i> using an intermediate auxiliary deep copy of <i>other</i>.
        /// </summary>
        /// <param name="source">the source matrix to copy from (may be identical to the receiver).</param>
        /// <returns><i>this</i> (for convenience only).</returns>
        /// <exception cref="ArgumentException">if <i>columns() != source.columns() || rows() != source.rows()</i></exception>
        public override ObjectMatrix2D Assign(ObjectMatrix2D source)
        {
            // overriden for performance only
            if (!(source is DenseObjectMatrix2D))
            {
                return(base.Assign(source));
            }
            DenseObjectMatrix2D other = (DenseObjectMatrix2D)source;

            if (other == this)
            {
                return(this);               // nothing to do
            }
            CheckShape(other);

            if (!this.IsView && !other.IsView)
            { // quickest
                Array.Copy(other.Elements, 0, this.Elements, 0, this.Elements.Length);
                return(this);
            }

            if (HaveSharedCells(other))
            {
                ObjectMatrix2D c = other.Copy();
                if (!(c is DenseObjectMatrix2D))
                { // should not happen
                    return(base.Assign(other));
                }
                other = (DenseObjectMatrix2D)c;
            }

            Object[] elems      = this.Elements;
            Object[] otherElems = other.Elements;
            if (Elements == null || otherElems == null)
            {
                throw new NullReferenceException();
            }
            int cs  = this.ColumnStride;
            int ocs = other.ColumnStride;
            int rs  = this.RowStride;
            int ors = other.RowStride;

            int otherIndex = other.Index(0, 0);
            int index      = base.Index(0, 0);

            for (int row = Rows; --row >= 0;)
            {
                for (int i = index, j = otherIndex, column = Columns; --column >= 0;)
                {
                    elems[i] = otherElems[j];
                    i       += cs;
                    j       += ocs;
                }
                index      += rs;
                otherIndex += ors;
            }
            return(this);
        }