Two for loops written as a while loop for assign values to a symmetric matrix
-
22-04-2021 - |
Frage
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?
Lösung
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.
Andere Tipps
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.