Last active
March 4, 2023 11:14
-
-
Save pavly-gerges/95f323f35c8285f64d322dbf01bfa5d3 to your computer and use it in GitHub Desktop.
Example showing matrix addition in c
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> | |
#include <stdlib.h> | |
int* mat_add(int*, int*, int); | |
int* mat_add(int* a, int* b, int enteries) { | |
// enteries * 4 = 2 * 4 = 8 bytes | |
int* summation = (int*) calloc(enteries, sizeof(int)); | |
for (int row = 0; row < enteries; row++) { | |
for (int column = 0; column < enteries; column++) { | |
int cell = row * enteries + column; | |
summation[cell] = a[cell] + b[cell]; | |
} | |
} | |
return summation; | |
} | |
int main() { | |
int a[2][2] = {{1,2}, | |
{3,4}}; | |
int b[2][2] = {{3,4}, | |
{5,6}}; | |
int* sum = mat_add(a, b, 2); | |
for (int row = 0; row < 2; row++) { | |
for (int column = 0; column < 2; column++) { | |
int cell = row * 2 + column; | |
printf("%d, ", sum[cell]); | |
} | |
printf("\n"); | |
} | |
free(sum); | |
return 0; | |
} |
Another simple solution by manipulating arrays in terms of linear memory buffers:
#include <stdio.h>
#include <stdlib.h>
int* mat_add(int*, int*, int);
int* mat_add(int* a, int* b, int enteries) {
// enteries * 4 = 2 * 4 = 8 bytes
int* summation = (int*) calloc(enteries, sizeof(int));
for (int cell = 0; cell < enteries * 2; cell++) {
summation[cell] = a[cell] + b[cell];
}
return summation;
}
int main() {
int a[2][2] = {{1,2},
{3,4}};
int b[2][2] = {{3,4},
{5,6}};
int* sum = mat_add(a, b, 2);
for (int row = 0; row < 2; row++) {
for (int column = 0; column < 2; column++) {
int cell = row * 2 + column;
printf("%d, ", sum[cell]);
}
printf("\n");
}
free(sum);
return 0;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another equivalent example: