-2

Here is my code below-

double[][] geometricReturnsArray = new double[returnsArray.Count][];;
double[] tempGeometricReturns = new double[returnsArray[0].Count];
double return_1 = 0;
double return_2 = 0;

        for (int i = 0; i < returnsArray.Count; i++)
        {
            for (int j = 0; j < returnsArray[i].Count - 1; j++)
            {
                return_1 = returnsArray[i][j + 1];
                return_2 = returnsArray[i][j];
                tempGeometricReturns[j] = ((return_1 - return_2) / return_2) * 100;
            }
            geometricReturnsArray[i] = tempGeometricReturns;
        }

The issue I'm facing in the code is that tempGeometricReturns keeps getting reassigned as i increases. So in the end, all three arrays of geometricReturnsArray have exactly the same values since when tempGeometricReturns gets reassigned, so do the previous values in geometricReturnsArray.

I tried to use lists as well but then I just get a long list of 267 values whereas I'd prefer three arrays of length 90. What else can I try to do?

travybel
  • 1
  • 4

1 Answers1

0

In your example you will end up with multiple references to the same array in the geometricReturnsArray. Arrays are reference types, so assignments only copy the reference, not the entire array.

The fix is to create a new array for each outer loop, for example by copying the existing array when doing the assignment

        }
            geometricReturnsArray[i] = tempGeometricReturns.ToArray();
    }

or

for (int i = 0; i < returnsArray.Count; i++)
{
    double[] tempGeometricReturns = new double[returnsArray[0].Count];
    for (int j = 0; j < returnsArray[i].Count - 1; j++)
    {
JonasH
  • 28,608
  • 2
  • 10
  • 23
  • "The fix is to create a new array for each outer loop" I agree. "for example by copying the existing array when doing the assignment" That seems strictly worse than just moving `double[] tempGeometricReturns = new double[returnsArray[0].Count];` inside the outer loop, which avoids the unnecessary copy. – Ben Voigt Jul 26 '21 at 17:13
  • @Ben voigt Agree, picked that option because it was simplest, And because most probably the difference will not be noticable. Still, added your variant for completeness. – JonasH Jul 27 '21 at 06:40