I want to store in an array a symmetric matrix
for a matrix I was doing this
double[,] mat = new double[size,size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j <= i; j++)
mat[i, j] = mat[j, i] = (n * other_matrix[i,j]);
}
If I want to store in an array
double[] mat = new double[size*size];
instead of
double[,] mat
What would be the most efficient way?
using mat[i*n+j]?
Yes.
Store the elements by row, where the
i-th row andj-th column is stored in indexk=i*NC+jwithNCthe number of columns. This applies to a non-symmetric general matrix.To store a symmetric matrix of size
Nyou only needN*(N+1)/2elements in the array. You can assume thati<=jsuch that the array indexes go like this:with
Example when N=5, the array indexes go like this
The total elements needed are
5*(5+1)/2 = 15and thus the indexes go from0..14.The
i-th diagonal has indexk(i,i) = i*(N+1)-i*(i+1)/2. So the 3rd row (i=2) has diagonal indexk(2,2) = 2*(5+1)-2*(2+1)/2 = 9.The last element of the
i-th row has index =k(i,N) = N*(i+1)-i*(i+1)/2-1. So the last element of the 3rd row isk(2,4) = 5*(2+1)-2*(2+1)/2-1 = 11.The last part that you might need is how to go from the array index
kto the rowiand columnj. Again assuming thati<=j(above the diagonal) the answer isTo check the above I run this for
N=5,k=0..14and got the following results:Which is correct!
To make the copy then just use
Array.Copy()on the elements which is super fast. Also to do operations such as addition and scaling you just need to work on the reduced elements in the array, and not on the fullN*Nmatrix. Matrix multiplication is a little tricky, but doable. Maybe you can ask another question for this if you want.