简体   繁体   中英

How to create a 3D List in C#

I have a list which is made up of 2 lists with the following numbers: list(1) = (2,3,5,3) list(2) = (1,3,9,2). Now I have to create two matrix: The first matrix 4x4 should have all the elements of list(1) on the diagonal, the rest of the numbers should be zero.

The second matrix 4x4 should have all the elements of list(2) on the diagonal. The rest of the numbers should be zero.

I want to do this with a for loop. Could you please help me? I don't know how to start, I'm new in C# and I can't find references in which it's clear how to work with 3D matrix as I did with Matlab. Thanks a lot!

Create a regular List<int> for the first list.

List<int> list = new List<int>() { 2, 3, 5, 3 };

Then your 'matrix'(which really is a 2D array):

int[,] matrix = new int[4, 4];

Now, the diagonal means column == row , so using two loops you can enter the value only when that condition is met.

for (int row = 0; row < list.Count; row++)
{
    for (int col = 0; col < list.Count; col++)
    {
        if (col == row)
            matrix[row, col] = list[row];
        else
            matrix[row, col] = 0;
    }
}

Confirmation:

在此处输入图片说明

And do the same thing for the 2nd list. You could easily write a function that would do this.

EDIT

Here it is put into a function, and how to use it.

static int[,] CreateMatrix(List<int> list)
{
    int[,] matrix = new int[list.Count, list.Count];

    for (int row = 0; row < list.Count; row++)
    {
        for (int col = 0; col < list.Count; col++)
        {
            if (col == row)
                matrix[row, col] = list[row];
            else
                matrix[row, col] = 0;
        }
    }

    return matrix;
}

Calling:

var list1 = new List<int>() { 2, 3, 5, 3 };
var list2 = new List<int>() { 1, 3, 9, 2 };

var matrix1 = CreateMatrix(list1);
var matrix2 = CreateMatrix(list2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM