Reputation: 3
Here is the code, for the 2D arrays a,b,c:
#include <stdio.h>
int main(){
int a[2][2]=
{
{1, 1},
{2, 2}
};
int b[2][2]=
{
{1, 1},
{2, 2}
};
int c[2][2]=
{
{1, 1},
{2, 2}
};
//Loop for 2D
int i,j,k, n=2;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
c[i][j] += a[i][k] * b[k][j];
printf("%i ",c[i][j]);
}
}
}
}
The result is: 2 4 2 4 4 8 4 8
I wrote this code, that converts the array c[i][j] into a 1D array. After running it I don't get the same result.
//Loop for 1D
int i,j,k, n=2, result[50];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
result[k] = c[i][j];
result[k] += a[i][k] * b[k][j];
printf("%i ", result[k]);
}
}
}
For this Loop the result is: 2 3 2 3 4 6 4 6
Upvotes: 0
Views: 3012
Reputation: 1
Create a global array as a calculated array of size 4*m where m is the number of 2x2 matrices. Then use a do while loop where the loop counter variable is used to calculate a pointer a group of four elements. Pass that pointer to a method that extracts the 2x2 matrice elements in a left to right, row by row fashion into the global array. Use pointer de referencing in the method but don't increment the pointer in the method. Upon return of the method if there are more groups of 4 elements to process recalculate the pointer and process the next 2x2 matrice. My pc is broken at the moment so i can describe this in code.
Upvotes: 0
Reputation: 4318
Maybe you want this index i+n*j
for the 1D array.
int i,j,k, n=2, result[50];
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
result[i+n*j] = c[i][j];
for (k = 0; k < n; k++) {
result[i+n*j] += a[i][k] * b[k][j];
printf("%i ", result[i+n*j]);
}
}
}
Upvotes: 2
Reputation: 141
c[i][j] is not changed in the second one. But it is changed in the first one.
Upvotes: 0