locked
string array into double array RRS feed

  • Question

  • Hi,

    I have the following snippet of code from Microsoft KB which loops through a 2-dimensional array:

    for (long rowCounter = 1; rowCounter <= 5; rowCounter++)
                    {
                        for (long colCounter = 4; colCounter <= 4; colCounter++)
                        {

                            //Write the next value into the string.
                            valueString2 = String.Concat(valueString2,
                               saRet[rowCounter, colCounter].ToString() + ", ");
                        }

                        //Write in a new line.
                        valueString2 = String.Concat(valueString2, "\n")

                    }

    What I'd like to do instead of passing to valuestring2, is pass those strings into a double[] arrayname.  So everytime it loops to the next value in the 2-d array it pass it it into a 1-d array (double[] arrayname. 

     

    Any help would be greatly appreciated.

     

     

    Friday, December 2, 2011 9:27 PM

Answers

  • I do not understand what you're trying to accomplish.

     

    You can convert a string[] to a double[] by

    double [] doubleArray = new double[stringArray.Length]
    
    for(int i=0; i<stringArray.Length; i++)
    {
         doubleArray[i] = Double.Parse(stringArray[i]);
    }
    

    or you can use linq

    double[] doubleArray = stringArray.Select<string, double>(s => Double.Parse(s)).ToArray<double>();
    


    • Proposed as answer by JMCF125 Wednesday, December 7, 2011 7:03 PM
    • Marked as answer by Bob ShenModerator Wednesday, December 14, 2011 2:43 AM
    Friday, December 2, 2011 9:45 PM
  • Hi,

    I have the following snippet of code from Microsoft KB which loops through a 2-dimensional array:

    for (long rowCounter = 1; rowCounter <= 5; rowCounter++)
                    {
                        for (long colCounter = 4; colCounter <= 4; colCounter++)
                        {

                            //Write the next value into the string.
                            valueString2 = String.Concat(valueString2,
                               saRet[rowCounter, colCounter].ToString() + ", ");
                        }

                        //Write in a new line.
                        valueString2 = String.Concat(valueString2, "\n")

                    }

    What I'd like to do instead of passing to valuestring2, is pass those strings into a double[] arrayname.  So everytime it loops to the next value in the 2-d array it pass it it into a 1-d array (double[] arrayname. 

     

    Any help would be greatly appreciated.

     

     

    Hi,

    do you want to put the elements of a 2d-array to a 1d-array?, like:

            private Random _rnd = new Random();
    
            private void button1_Click(object sender, EventArgs e)
            {
                //the 2d-array
                byte[,] myMatrix = new byte[200, 200];
    
                //fill with random (color-) values
                for (int y = 0; y < myMatrix.GetLength(1); y++)
                {
                    for (int x = 0; x < myMatrix.GetLength(0); x++)
                    {
                        myMatrix[x, y] = (byte)_rnd.Next(256);
                    }
                }
    
                //the new 1d-array
                byte[] pixels = new byte[myMatrix.GetLength(0) * myMatrix.GetLength(1)];
    
                //convert the 2 dimensional array into a one dimensional byte-array
                for (int y = 0; y < myMatrix.GetLength(1); y++)
                {
                    for (int x = 0; x < myMatrix.GetLength(0); x++)
                    {
                        pixels[y * myMatrix.GetLength(0) + x] = myMatrix[x, y];
                    }
                }
            }

    Regards,

    Thorsten

    Friday, December 2, 2011 11:15 PM

All replies

  • I do not understand what you're trying to accomplish.

     

    You can convert a string[] to a double[] by

    double [] doubleArray = new double[stringArray.Length]
    
    for(int i=0; i<stringArray.Length; i++)
    {
         doubleArray[i] = Double.Parse(stringArray[i]);
    }
    

    or you can use linq

    double[] doubleArray = stringArray.Select<string, double>(s => Double.Parse(s)).ToArray<double>();
    


    • Proposed as answer by JMCF125 Wednesday, December 7, 2011 7:03 PM
    • Marked as answer by Bob ShenModerator Wednesday, December 14, 2011 2:43 AM
    Friday, December 2, 2011 9:45 PM
  • Hi,

    I have the following snippet of code from Microsoft KB which loops through a 2-dimensional array:

    for (long rowCounter = 1; rowCounter <= 5; rowCounter++)
                    {
                        for (long colCounter = 4; colCounter <= 4; colCounter++)
                        {

                            //Write the next value into the string.
                            valueString2 = String.Concat(valueString2,
                               saRet[rowCounter, colCounter].ToString() + ", ");
                        }

                        //Write in a new line.
                        valueString2 = String.Concat(valueString2, "\n")

                    }

    What I'd like to do instead of passing to valuestring2, is pass those strings into a double[] arrayname.  So everytime it loops to the next value in the 2-d array it pass it it into a 1-d array (double[] arrayname. 

     

    Any help would be greatly appreciated.

     

     

    Hi,

    do you want to put the elements of a 2d-array to a 1d-array?, like:

            private Random _rnd = new Random();
    
            private void button1_Click(object sender, EventArgs e)
            {
                //the 2d-array
                byte[,] myMatrix = new byte[200, 200];
    
                //fill with random (color-) values
                for (int y = 0; y < myMatrix.GetLength(1); y++)
                {
                    for (int x = 0; x < myMatrix.GetLength(0); x++)
                    {
                        myMatrix[x, y] = (byte)_rnd.Next(256);
                    }
                }
    
                //the new 1d-array
                byte[] pixels = new byte[myMatrix.GetLength(0) * myMatrix.GetLength(1)];
    
                //convert the 2 dimensional array into a one dimensional byte-array
                for (int y = 0; y < myMatrix.GetLength(1); y++)
                {
                    for (int x = 0; x < myMatrix.GetLength(0); x++)
                    {
                        pixels[y * myMatrix.GetLength(0) + x] = myMatrix[x, y];
                    }
                }
            }

    Regards,

    Thorsten

    Friday, December 2, 2011 11:15 PM
  • Something like this?
    int i = 0;
    double[] array1D = new double[array2D.Length];
    foreach(double d in array2D)
    {
            array1D[i] = d;
            i++;
    }
    

    Monday, December 5, 2011 1:00 PM
  • So, I'm literally trying to take this piece of code from the above snippet:

     

     String.Concat(valueString2,saRet[rowCounter, colCounter].ToString() + ", ");

     

    and pass it into a double[]  array.  For some reason I'm stuck on this portion. 

    Wednesday, December 7, 2011 2:24 PM
  • So if I get this correctly, you have a 2-dimensional string array, where all of the elements in the string array are actually numeric, and you want to convert it to a 1-dimensional double array? If I were doing that, I'd do something like this:

    List<double> result = new List<double>();

    for (int row = 0; row < saRet.Length; row++)

    {

            string[] innerArray = saRet[row];

            for (int col=0; col < innerArray.Length; col++)

            {

                    result.Add(Double.Parse(innerArray[col]);

            }

    }

    return result.ToArray();

     


    Check out My Blog for tech news, development tips, and other information for geeks like me.
    Wednesday, December 7, 2011 3:09 PM
  • I thought I just did that.

    The only other meaning would be that you want to put the result of the String.Concat into a double array, but it doesn't make much sense.

    Thursday, December 8, 2011 2:42 PM
  •         string[] innerArray = saRet[row];
    This cannot work on a multidimensional array. It would work with a jagged array.
    Thursday, December 8, 2011 2:45 PM
  • I thought I just did that.

    The only other meaning would be that you want to put the result of the String.Concat into a double array, but it doesn't make much sense.

    You just copied a 2d double array to a 1d double array. He's dealing with strings, apparently. Plus, unless I'm misreading, yours only gets the first dimension of the 2d array - if he needs to collapse the two arrays, you need to loop through both dimensions.

    I'm not sure what you mean about it not working on a multidimensional array...I believe the code I wrote should work for any 2d array (of which a jagged array is one type). What would prevent it from working for 2-dimensional arrays which are not jagged?


    Check out My Blog for tech news, development tips, and other information for geeks like me.
    Thursday, December 8, 2011 3:39 PM
  • You just copied a 2d double array to a 1d double array. He's dealing with strings, apparently.

    Right. My code needs to be changed from

    array1D[i] = d;
    

    to

    array1D[i] = double.Parse(d);
    

    Plus, unless I'm misreading, yours only gets the first dimension of the 2d array - if he needs to collapse the two arrays, you need to loop through both dimensions.

    The foreach loops goes from the first item of the array to the last.

    I'm not sure what you mean about it not working on a multidimensional array...I believe the code I wrote should work for any 2d array (of which a jagged array is one type).

    A jagged array is not a multidimensional array, it's an array of arrays

    What would prevent it from working for 2-dimensional arrays which are not jagged?

    Specifying only the first rank of a multi-dimensional array won't extract a sub-array. It's a syntax error. The equivalent of your code for a multidimensional array would be:

    List<double> result = new List<double>();
    for (int row = 0; row < saRet.GetLength(0); row++)
    {
            for (int col=0; col < saRet.GetLength(1); col++)
            {
                    result.Add(Double.Parse(saRet[row, col]));
            }
    }
    return result.ToArray();
    

    Since you know the size of the array from the start, you don't need a temporary List:

    double[] result = new double[saRet.Length];
    int i = 0;
    for (int row = 0; row < saRet.GetLength(0); row++)
    {
            for (int col=0; col < saRet.GetLength(1); col++)
            {
                    result[i++] = Double.Parse(saRet[row, col]);
            }
    }
    return result;
    
    Note that this code works only for a two-dimensional array, while the foreach can handle any rank.
    Thursday, December 8, 2011 4:33 PM
  • I get what you're saying at this point - this is just a slip up in terminology. Jagged arrays and multidimensional arrays are logically the same thing, but there is a difference in the .Net framework in syntax. In logical terms, a multidimensional array is also an array of arrays. They are two different things in .net only because CIL provides different implementations for usability sake (though I still avoid multidimensional arrays whenever humanly possible, which is why I forgot they even existed). Above, where I use the term "multidimensional array", you can assume I meant "jagged array".

    From the opening post and the logic being used, I believe it's pretty obvious that the OP is also talking about a jagged array and not a multidimensional array in .Net framework terms. So, the whole semantic conversation is interesting and you did remind me of a framework "feature" which I had forgotten about, I don't really think it contributes anything to the actual question.


    Check out My Blog for tech news, development tips, and other information for geeks like me.
    Thursday, December 8, 2011 5:10 PM
  • I get what you're saying at this point - this is just a slip up in terminology. Jagged arrays and multidimensional arrays are logically the same thing, but there is a difference in the .Net framework in syntax. In logical terms, a multidimensional array is also an array of arrays. They are two different things in .net only because CIL provides different implementations for usability sake (though I still avoid multidimensional arrays whenever humanly possible, which is why I forgot they even existed). Above, where I use the term "multidimensional array", you can assume I meant "jagged array".

    From the opening post and the logic being used, I believe it's pretty obvious that the OP is also talking about a jagged array and not a multidimensional array in .Net framework terms. So, the whole semantic conversation is interesting and you did remind me of a framework "feature" which I had forgotten about, I don't really think it contributes anything to the actual question.


    Check out My Blog for tech news, development tips, and other information for geeks like me.

    No, there is more than just a syntactical difference.  A Mutidimensional array in C# is actually a single dimensional array (for performance reasons).  That single dimensional array is actually of length (rows*columns).  When accessing it via [row, column] it converts that to [row*rowMax+column] in the underlying single dimensional array.

    A jagged array is actually an array of pointers to 'row' number of other independently allocated arrays of length 'column'.

    You cannot set an entire row of columns of a multidimensional array to be another array (of length 'column') but with a jagged array you can (you are just changing the pointer at the index of row to point to a new array).  For a multidimensional array to set an entire row you simply need to overwrite the value for each cell in that row.  This same logic applies to getting an array representing the row as well as for setting it.  For a jagged array you're just copying the pointer to that row's array, for a multidimensional array you need to make a new array and copy the values for each row in the cell.

    Friday, December 9, 2011 3:14 PM
  • I get what you're saying at this point - this is just a slip up in terminology. Jagged arrays and multidimensional arrays are logically the same thing, but there is a difference in the .Net framework in syntax. In logical terms, a multidimensional array is also an array of arrays. They are two different things in .net only because CIL provides different implementations for usability sake (though I still avoid multidimensional arrays whenever humanly possible, which is why I forgot they even existed). Above, where I use the term "multidimensional array", you can assume I meant "jagged array".

    From the opening post and the logic being used, I believe it's pretty obvious that the OP is also talking about a jagged array and not a multidimensional array in .Net framework terms. So, the whole semantic conversation is interesting and you did remind me of a framework "feature" which I had forgotten about, I don't really think it contributes anything to the actual question.


    Check out My Blog for tech news, development tips, and other information for geeks like me.

    No, there is more than just a syntactical difference.  A Mutidimensional array in C# is actually a single dimensional array (for performance reasons).  That single dimensional array is actually of length (rows*columns).  When accessing it via [row, column] it converts that to [row*rowMax+column] in the underlying single dimensional array.

    A jagged array is actually an array of pointers to 'row' number of other independently allocated arrays of length 'column'.

    You cannot set an entire row of columns of a multidimensional array to be another array (of length 'column') but with a jagged array you can (you are just changing the pointer at the index of row to point to a new array).  For a multidimensional array to set an entire row you simply need to overwrite the value for each cell in that row.  This same logic applies to getting an array representing the row as well as for setting it.  For a jagged array you're just copying the pointer to that row's array, for a multidimensional array you need to make a new array and copy the values for each row in the cell.

    What you're describing is just a syntactical difference. In logical terms, both are modeled as a logical grid - they are two different technical implementations of the same logical construct. The only difference is in the CLR and language implementation, not in the conceptual construct itself. That's what I was suggesting - I realize the code would have to be different to deal with a multidimensional array, but it really is just another representation of the same conceptual construct. Think of it like this - you could implement a Stack class using an array or a linked list behind-the-scenes. Regardless which one you use, the logical behavior of a Stack hasn't changed, only the implementation details and (in many cases) the public interface. The definition of a "stack" in conceptual terms is still exactly the same. That's how multi-dimensional arrays and jagged arrays are - the conceptual definition is identical, only the implementation differs.

    As a side note, while you would think the multidimensional array is a single dimension for performance reasons, it has actually been demonstrated to be slower than a jagged array (at least on Windows, not sure about Mono or other environments). That is the primary reason I avoid them - they don't really simplify readability or usability much, and they don't provide the performance improvement you would expect.

    All of that aside, while this is an interesting discussion (and I'd be happy to continue it in a discussion thread) it's not really relevant to this thread. The original post was obviously talking about jagged arrays, and that's what my response was intended to address, I just got terminology mixed up when I was talking about it.


    Check out My Blog for tech news, development tips, and other information for geeks like me.
    Friday, December 9, 2011 3:21 PM
  • From the opening post and the logic being used, I believe it's pretty obvious that the OP is also talking about a jagged array and not a multidimensional array in .Net framework terms.

    From the opening post and the syntax used, it's pretty obvious saRet is a multi-dimensional array, not a jagged array.
    Tuesday, December 13, 2011 1:49 PM
  • Regardless which one you use, the logical behavior of a Stack hasn't changed, only the implementation details and (in many cases) the public interface. The definition of a "stack" in conceptual terms is still exactly the same. That's how multi-dimensional arrays and jagged arrays are - the conceptual definition is identical, only the implementation differs.

    A jagged array can be used a lot like a multi-dimensional array. To change code from using a multi-dimensional array to using a jagged array, you need only to change the allocation and the syntax to access it. Most of the time. Except when you cannot use a jagged array because you don't know the number of dimensions, only the total size, or because you pass it to unmanaged code.

    But, the reverse is not true. As already stated, any code returning one of the subarrays would need to make a copy of a part of a multi-dimensional array. And what about non-rectangular arrays? If it's only an implementation detail, I'm curious to see how straight-forward it is to have the following method using a multi-dimensional array as parameter (without losing functionality):

    int[] Averages(int[][] results)
    {
            int[] avg = new int[results.Length];
            for(int i = 0; i < results.Length; i++)
            {
                    int sum = 0;
                    for(int j = 0; j < results[i].Length; j++)
                    {
                            sum += results[i][j];
                    }
                    avg[i] = sum/results[i].Length;
            }
    }
    

     

    Tuesday, December 13, 2011 2:04 PM
  • Really? The thread is this old, and you're still working on reviving it for an argument?

    You win. You're the smartest. Can the thread end now?


    Check out My Blog for tech news, development tips, and other information for geeks like me.
    Tuesday, December 13, 2011 2:33 PM
  • It's not that old. I didn't revive it. It's not even marked as answered.

    I don't think I need to prove anything to anyone, so trying to have the last word with sentences like "ok, you win, you're the smartest" don't work with me. You think I won't reply lest I look arrogant or something?

    I'm not trying to be the smartest, I was just explaining why I wasn't wrong. Demonstrate that I was wrong and I won't argue. But don't try making me look like I think I'm superior to you all puny humans.

    Tuesday, December 13, 2011 4:10 PM
  • I'm not trying to make it look like anything. You have a habit of turning threads into arguments and pointing out where other answerers are wrong on mostly irrelevant points. You were correct, like I said. Even so, your suggestions haven't actually added much of anything to the original question since at least December 8.

    I'm done with arguments, it takes more energy than it's worth. My new tact is just to agree that you are correct (which you legitimately usually are) and move on with life instead of giving you the fodder to turn perfectly good threads like this into arguments.


    Check out My Blog for tech news, development tips, and other information for geeks like me.
    Tuesday, December 13, 2011 5:50 PM
  • You have a habit of turning threads into arguments and pointing out where other answerers are wrong on mostly irrelevant points.
    I didn't realise I did that. I won't argue anymore. Sorry for the disturbance.
    Tuesday, December 20, 2011 9:59 AM