Created
May 9, 2016 15:39
-
-
Save besza/8173337d5c1ba5e080d3224f60ccdb15 to your computer and use it in GitHub Desktop.
Transform NxN upper triangular matrix to a 1D row-major vector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
// fhm - felso haromszog matrix | |
// nxn-es fhm nem-nulla elemeinek a szamossaga | |
int fhm_elemei(int n) | |
{ | |
return (n*n + n)/2; | |
} | |
// lekepezes ami megadja hogy M nxn-es fhm i-edik soranak | |
// j-edik eleme hanyadik indexu eleme az fhm-et reprezentalo | |
// sorfolytonos 1-dim vektorban | |
int f(int i, int j, int n) | |
{ | |
return j >= i ? (n * i + j - (i*i + i)/2) : -1; | |
} | |
void print_vec(int n, int* vec) | |
{ | |
printf("%s", "["); | |
for (int j = 0; j < n; ++j) | |
{ | |
printf("%d,", vec[j]); | |
} | |
printf("%s", "]"); | |
} | |
int main() | |
{ | |
int n = 4; | |
int k = 1; | |
int m[n][n]; | |
int len = fhm_elemei(n); | |
int vec[len]; | |
//feltoltes | |
for (int i = 0; i < n; ++i) | |
{ | |
for (int j = 0; j < n; ++j) | |
{ | |
if (j >= i) | |
{ | |
m[i][j] = k++; | |
} | |
else | |
{ | |
m[i][j] = 0; | |
} | |
} | |
} | |
/* | |
m : | |
[1,2,3,4] | |
[0,5,6,7] | |
[0,0,8,9] | |
[0,0,0,10] | |
*/ | |
//atalakitas sorfolytonossa | |
for (int i = 0; i < n; ++i) | |
{ | |
for (int j = 0; j < n; ++j) | |
{ | |
if (j >= i) | |
{ | |
int idx = f(i,j,n); | |
if (idx != -1) | |
{ | |
vec[idx] = m[i][j]; | |
} | |
} | |
} | |
} | |
print_vec(len, vec); //prints [1,2,3,4,5,6,7,8,9] | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment