Example #1
0
        /// <summary>
        /// Returns the content of the Rexp as a matrix of doubles (2D-array: m[rows][cols]).
        /// </summary>
        /// <returns>2D array of doubles in the form double[rows][cols] or
        /// <code>null</code> if the contents is no 2-dimensional matrix of doubles
        /// </returns>
        /// <example>Double[,] m=RconnectionObject.Eval("matrix(c(1,2,3,4,5,6),2,3)").AsDoubleMatrix();</example>
        public Double[,] AsDoubleMatrix()
        {
            if ((type != Xpression.XT_ARRAY_DOUBLE) || (rattribute == null) ||
                (rattribute.Xtype != Xpression.XT_LIST))
            {
                return(null);
            }

            Rexp dim = rattribute.AsList().Head;

            if (dim == null || dim.Xtype != Xpression.XT_ARRAY_INT)
            {
                return(null);                                                    // we need dimension attr
            }
            Int32[] ds = dim.AsIntArray();
            if (ds == null || ds.Length != 2)
            {
                return(null);                              // matrix must be 2-dimensional
            }
            Int32 m = ds[0];
            Int32 n = ds[1];

            Double[,] r = new Double[m, n];
            Double[] ct = AsDoubleArray();
            if (ct == null)
            {
                return(null);
            }
            // R stores matrices as matrix(c(1,2,3,4),2,2) = col1:(1,2), col2:(3,4)
            // we need to copy everything, since we create 2d array from 1d array
            Int32 k = 0;

            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    r[i, j] = ct[k++];
                }
            }
            return(r);
        }