Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

language agnostic - How to store a symmetric matrix?

Which is the best way to store a symmetric matrix in memory?

It would be good to save half of the space without compromising speed and complexity of the structure too much. This is a language-agnostic question but if you need to make some assumptions just assume it's a good old plain programming language like C or C++..

It seems a thing that has a sense just if there is a way to keep things simple or just when the matrix itself is really big, am I right?

Just for the sake of formality I mean that this assertion is always true for the data I want to store

matrix[x][y] == matrix[y][x]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a good method to store a symmetric matrix, it requires only N(N+1)/2 memory:

int fromMatrixToVector(int i, int j, int N)
{
   if (i <= j)
      return i * N - (i - 1) * i / 2 + j - i;
   else
      return j * N - (j - 1) * j / 2 + i - j;
}

For some triangular matrix

0 1 2 3
  4 5 6
    7 8
      9

1D representation (stored in std::vector, for example) looks like as follows:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

And call fromMatrixToVector(1, 2, 4) returns 5, so the matrix data is vector[5] -> 5.

For more information see http://www.codeguru.com/cpp/cpp/algorithms/general/article.php/c11211/TIP-Half-Size-Triangular-Matrix.htm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...