Skip to content

Instantly share code, notes, and snippets.

@apzzd
Last active May 21, 2024 19:57
Show Gist options
  • Save apzzd/bf46d5768c9ba21a1edda966beb09f3d to your computer and use it in GitHub Desktop.
Save apzzd/bf46d5768c9ba21a1edda966beb09f3d to your computer and use it in GitHub Desktop.
✨ c code for multiplying two 2x2 matrices, with arguments ✨
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
// first, making all these variables to use later
float matrix1[4];
float matrix2[4];
int i;
char* token;
char* rest;
// splitting first arg by ", " and assigning the values to the first matrix
rest = argv[1];
i=0;
while ((token = strtok_r(rest, ", ", &rest))) {
matrix1[i] = atof(token);
i++;
}
// doing it again for the second matrix
rest = argv[2];
i=0;
while ((token = strtok_r(rest, ", ", &rest))) {
matrix2[i] = atof(token);
i++;
}
// printing out both matrices
printf("\n(%g %g) (%g %g)", matrix1[0], matrix1[1], matrix2[0], matrix2[1]);
printf("\n(%g %g) (%g %g)", matrix1[2], matrix1[3], matrix2[2], matrix2[3]);
// multiplying them! this is really long so i put it on several lines
float product[] = {
(matrix1[0] * matrix2[0]) + (matrix1[1] * matrix2[2]),
(matrix1[0] * matrix2[1]) + (matrix1[1] * matrix2[3]),
(matrix1[2] * matrix2[0]) + (matrix1[3] * matrix2[2]),
(matrix1[2] * matrix2[1]) + (matrix1[3] * matrix2[3])
};
// printing out the product of the two matrices
printf("\n\n _ (%g %g)", product[0], product[1]);
printf("\n ¯ (%g %g)\n", product[2], product[3]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment