Converts a vector into a rectangular array. - CSharp System

CSharp examples for System:Array Convert

Description

Converts a vector into a rectangular array.

Demo Code


using System;//from  w  w w.j a v  a2 s .  c  om

public class Main{
        // TODO: probably room for extension methods around Matrix inheritors
        /// <summary>
        /// Converts a vector into a rectangular array.
        /// Vector to matrix augmentation is done column first, i.e. "appending" successive lines to the bottom of the new matrix
        /// </summary>
        /// <typeparam name="U">The type of the output array elements</typeparam>
        /// <param name="array">Input array</param>
        /// <param name="rows">The number of rows in the output</param>
        /// <param name="cols">The number of columns in the output</param>
        /// <returns></returns>
        public static U[,] ArrayConvertAllTwoDim<U>(U[] array, int rows, int cols)
        {
            return ArrayConvertAllTwoDim(array, value => value, rows, cols);
        }
        // TODO: probably room for extension methods around Matrix inheritors
        /// <summary>
        /// Convert all elements of a vector into a rectangular array, using a function to cast/transform each element.
        /// Vector to matrix augmentation is done column first, i.e. "appending" successive lines to the bottom of the new matrix
        /// </summary>
        /// <typeparam name="T">The type of the input array elements</typeparam>
        /// <typeparam name="U">The type of the output array elements</typeparam>
        /// <param name="array">Input array</param>
        /// <param name="fun">A conversion function taking in an object of type T and returning one of type U</param>
        /// <param name="rows">The number of rows in the output</param>
        /// <param name="cols">The number of columns in the output</param>
        /// <returns></returns>
        public static U[,] ArrayConvertAllTwoDim<T, U>(T[] array, Func<T, U> fun, int rows, int cols)
        {
            if (cols < 0) throw new ArgumentException("negative number for column numbers");
            if (rows < 0) throw new ArgumentException("negative number for row numbers");
            if (array.Length < (rows * cols)) throw new ArgumentException("input array has less than rows*cols elements");
            U[,] res = new U[rows, cols];
            for (int i = 0; i < rows; i++)
                for (int j = 0; j < cols; j++)
                    res[i, j] = fun(array[rows * j + i]);
            return res;
        }
}

Related Tutorials