Compression storage of symmetric matrices and symmetric matrices

Source: Internet
Author: User

Set a n*n square a,a any element Aij, when and only if Aij = = Aji(0 <= i <= N-1 && 0 <= J <= N-1), then matrix A is a symmetric matrix. Separated by the diagonal of the matrix, it is divided into upper and lower triangles.


Compressed storage is called a matrix storage only need to store the upper triangle/lower triangle of data, so the maximum storage N (n+1)/2 data.

symmetric matrix and compressed storage correspondence: Lower triangle storage i>=j, Symmetricmatrix[i][j] = = array[i* (i+1)/2+j]

650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>

0 1 2) 3 4

1 0 1) 2 3

2 1 0) 1 2

3 2 1) 0 1

4 3 2) 1 0

Symmetry.h in template < class t>class symmetry{public://constructor symmetry (T* arr,  size_t size): _arr (new t[size* (size+1)/2),  _size (size* (size + 1)/2) {for  ( int i = 0; i < size; i++) {for  (int j = 0; j  < size; j++) {if  (i >= j) {_arr[i* (i + 1)  / 2 +  j] = arr[i*size + j];//compress the symmetric matrix}}}}//print Void print (size_t size) {for  ( int i = 0; i < size; i++) {for  (int j = 0; j  < size; j++) {int row = i;int col = j;if  (row <  col) {swap (row, col);} cout << _arr[row* (row+ 1)  / 2 + col] <<  " ";} Cout << endl;} Cout << endl;} protected:t *_arr;size_t _size;}; In Test.cpp#include  <iostream>using namespace std; #include   "Symmetry.h" void test () {int  arr[5][5] = {{0,1,2,3,4},{1,0,1,2,3},{2,1,0,1,2},{3,2,1,0,1},{4,3,2,1,0}}; Symmetry<int>s ((int*) arr, 5); S.print (5);} Int main () {Test (); System ("pause"); return 0;}


Compression storage of symmetric matrices and symmetric matrices

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.