Reputation: 173
I'm trying to concatenate the same matrix in C, and the only idea that crossed to my mind is addition, but it doesn't work. For example, if I have: {1,1;2,2}
, my new matrix should be {1,1,1,1;2,2,2,2}
. I want to double the number of rows. I Googled, but I didn't find anything.
Here is my code:
matrix2=realloc(matrix1,sizeof(int*)*(row));
int i,j;
for(i=0;i<row;i++){
for(j=0;j<col;j++){
matrix2[i][j]=matrix1[i][j]+matrix1[i][j];
}
}
Upvotes: 2
Views: 5180
Reputation: 5452
Use the psuedocode I provide below. Note that for any C before C99, you cannot instantiate arrays with int matrix[2*W][H]
(if W and H are not #define
s)
Given matrix1 and matrix 2 of equal W,H
make matrix3 of 2*W,H
for h to H
for i to W
matrix3[h][i] = matrix1[h][i]
matrix3[h][i+W] = matrix2[h][i]
Making the matrix will require 1 malloc per row, plus 1 malloc to store the array of row pointers.
Note how you will need 2 assignments in the loop instead of the one you had before. This is because you are setting in two places.
Upvotes: 2
Reputation: 31
Here we are copying the input matrix into a new matrix twice
for(int i = 0; i < m; i++){for(int j = 0; j < n;j++) { mat2[i][j] = mat[i][j];}}
for(int i = 0 ; i < m ; i++){for(int j = n; j < (2*n) ; j++){ mat2[i][j] = mat[i][j-n];}}
Upvotes: 1
Reputation: 613
You sound like you have a background with higher level languages like matlab. In C the plus operator does not concatenate matrices. This will add the values in the matrices and store the new value into the new matrix.
Upvotes: 1