Splitting a 2D array to an array of smaller 2D arrays in C -
given:
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
i want split 2d array (struct matrix) array of struct matrix given chunksize cs: assume cs 2, answer be
seg[0]: 1 2 1 2 1 2 seg[1]: 3 4 3 4 3 4 .... seg[3]: 7 8 7 8 7 8
here matrix struct:
typedef struct matrix { int nrow; int ncol; int **element; } matrix;
and here function seperates them:
void segmentmatrix(matrix input,matrix* segs,int chunksize, int p) { int i,j,r; //allocate segs (i = 0; i<p;i++) { creatematrix(&(segs[i]),input.nrow ,chunksize,0); } //now copy elements input segs //where seg0 takes 0 cs cols of a, , rows, , seg1 takes cs 2cs ... printf("stats:\n\t p: %d\t cs: %d\n",p,chunksize); (r = 0; r<p; r++) { (i = 0; i<input.nrow;i++) { (j = r*chunksize; j<r*chunksize+chunksize-1; j++) { //i tried (&(segs[r]))->element... doesn't work, produces wrong data segs[r].element[i][j] = input.element[i][j]; } } printm(segs[r]); } }
note printm prints matrix, knows limits checking segs[r].nrow , ncol , creatematrix takes following inputs (&matrix, number of rows, number of colums, filltype) , mallocs within.
filltype: 0- generates zeroth matrix 1- generates identity else a[i][j] = j; simplicity
the problem if print matrices segs[i], come down default value given creatematrix, , not newly added values.
clarification: okay, if guys check last printm in segmentmatrix function, outputs matrices if loops didn't happen, aka, can delete loops , same output.. did wrong in line (taken segmentmatrix)
segs[r].element[i][j] = input.element[i][j];
i don't see why , manipulating multiplication chunksize
, r
(which uninitialized anyway), i'd suggest simplifying code (rule of thumb: if seems messy, it's complex). need 3-dimensional array store array of chunks, , modulo arithmetic plus integer division insert appropriate column of appropriate chunk:
/* variable-sized dimension of `chunks' argument w / chsz elements big * (it's number of chunks) */ void split(int h, int w, int mat[h][w], int chsz, int chunks[][h][chsz]) { /* go through each row */ (int = 0; < h; i++) { /* , in each row, go through each column */ (int j = 0; j < w; j++) { /* , each column, find chunk goes in * (that's j / chsz), , put proper row * (which j % chsz) */ chunks[j / chsz][i][j % chsz] = mat[i][j]; } } }
demonstration, a. k. a. how call it:
int main(int agrc, char *argv[]) { const size_t w = 8; const size_t h = 3; const size_t c = 2; int mat[h][w] = { { 1, 2, 3, 4, 5, 6, 7, 8 }, { 1, 2, 3, 4, 5, 6, 7, 8 }, { 1, 2, 3, 4, 5, 6, 7, 8 } }; int chunks[w / c][h][c]; split(h, w, mat, c, chunks); (int = 0; < w / c; i++) { (int j = 0; j < h; j++) { (int k = 0; k < c; k++) { printf("%3d ", chunks[i][j][k]); } printf("\n"); } printf("\n\n"); } return 0; }
Comments
Post a Comment