1

I have array with data. Array length equals 25 elements. I would like create matrix (5X5). How I can do this in C#? Please help.

1
  • That means you need a filter between a 1-dimensional array and a 2-dimensional array? Commented Mar 14, 2018 at 11:32

3 Answers 3

3

Translating a single dimension array into a multi dimension array is straight forward.

public static T getEntry<T>(this T[] array, int column, int row, int width)
{
  return array[column+row*width];
}

Add wrapper classes and/or validation as desired.

Usage example:

var array=Enumerable.Range(1,25).ToArray();
for (int row = 0; row  < 5; row ++)
    {
        for (int column = 0; column  < 5; column  ++)
        {
            Console.WriteLine("Value in column {0}, row {1} is {2}", column, row, array.getEntry(column,row));
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Can you create execution method because I do not know what does mean parameters 'x' and 'y'?
@DawidMalczak parameters renamed.
1

As @Taemyr suggest you can simply use indexing to simulate the structure of the matrix. If you need to access the element at row 2, col 3 in a 5 by 5 matrix simply access index 2*5+3 of your array. (row * # of cols + col)

If you want to split your array into a 2D array you can do so using the following code:

public static T[,] Matrix<T>(T[] arr, int rows) {
    var cols = arr.Length / rows;
    var m = new T[rows, cols];
    for (var i = 0; i < arr.Length; i++)
        m[i / cols, i % cols] = arr[i];
    return m;
} 

Comments

0

You can use Buffer.BlockCopy

using System;

class Test
{
    static double[,] ConvertMatrix(double[] flat, int m, int n)
    {
        if (flat.Length != m * n)
        {
            throw new ArgumentException("Invalid length");
        }
        double[,] ret = new double[m, n];
        // BlockCopy uses byte lengths: a double is 8 bytes
        Buffer.BlockCopy(flat, 0, ret, 0, flat.Length * sizeof(double));
        return ret;
    }

    static void Main()
    {
        double[] d = { 2, 5, 3, 5, 1, 6 };

        double[,] matrix = ConvertMatrix(d, 3, 2);

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                Console.WriteLine("matrix[{0},{1}] = {2}", i, j, matrix[i, j]);
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.