简体   繁体   中英

load txt file (m x n matrix) into 2d double array

I would like to load data from my txt file and store them in a 2D double array. I was trying something like this:

String input = File.ReadAllText(@"E:\c\vstup.txt");

int k = 0, l = 0;
double[][] resultout = new double[52][];
foreach (var row in input.Split('\n'))
{
    l = 0;
    foreach (var col in row.Trim().Split(' '))
    {
        resultout[k][l] = double.Parse(col.Trim());
        l++;
    }
    k++;
}

It is not working. I am new in C#. Can anyone suggest how to do this? Thank you.

EDIT: It throws NullReferenceException at the line: resultout[k][l] = double.Parse(col.Trim());

You do not initialize each row. In line:

double[][] resultout = new double[52][];

you initialize an array of 52 elements of type double[] , but they are not initialized. So when you are trying to:

resultout[k][l] = double.Parse(col.Trim());

it simply means you try to get l element of not existing array while resultout[k] is simply null . You have to initialize each row:

resultout[k] = new double[number_of_elements];

where number_of_elements you have to know before, for example:

var values = row.Trim().Split(' ');
resultout[k] = new double[values.Count()];
foreach (var col in values)
{
    resultout[k][l] = double.Parse(col.Trim());
    l++;
}

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