0

I know the logic two get into a symmetric matrix the values of an array

int k=0;
for (int i = 0; i < size; i++){
     for (int j = 0; j <= i; j++){                
          Q[i, j] = Q[j, i]= arr[k++];
     }
}

But How to do this if I can only use a while loop?

I was doing something like:

int i=0;
int j=0;
while (reader.Read())
{
   Q[i, j] = Q[j, i]=reader.GetDouble(1);
   if (j < i){
      j++;
   }else{
      j = 0;
      i++;
   }
}

Is the logic correct, How to improve this code?

edgarmtze
  • 24,683
  • 80
  • 235
  • 386
  • 1
    What's the reason for *not* using two nested for loops? The first approach looks much more readable. – Ondrej Tucny Feb 04 '12 at 19:35
  • I am reading the result of a Query in SQL, and I am only interested in the results of one of the results of the query and this results I want to put them in a symmetric matrix `Q[i,j]= Q[j,i]` but do not know how to – edgarmtze Feb 04 '12 at 19:37

2 Answers2

3

I personally think the while loop looks less clean than the nested for loop. I'd think just adding an extra conditional like this would work:

int k=0;
for (int i = 0; i < size; i++){
     for (int j = 0; j <= i && reader.Read(); j++){                
          Q[i, j] = Q[j, i]= reader.GetDouble(1);
     }
}

If reader returns false before your matrix is full it will spend some cycles going through the i loop, but it should be simple to improve if that's a concern.

Michael Yoon
  • 1,606
  • 11
  • 9
  • 1
    Indeed. To quote Brian Kernighan, “Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?” – rob mayoff Feb 04 '12 at 19:37
1

First look at my answer on how to represent a symmetric matrix with a 1D array here:

https://stackoverflow.com/a/9040526/380384

So you can assign the values like this

int k = 0;
while (reader.Read())
{
   A[k++] = reader.GetDouble(1);
}
int size = (int)(Math.Sqrt(2*k+0.25)-0.5);

given that only size*(size+1) values are needed to be entered.

Community
  • 1
  • 1
John Alexiou
  • 28,472
  • 11
  • 77
  • 133