# Matrix Multiplication using text file in C

Home » Programming » C Programming » Matrix Multiplication using text file in C

How to perform matrix multiplication in C programming language using text file? If this is the question that brought you to this website then you are in right place. In this article, you will learn how to do matrix multiplication by reading the two matrices from the two text files and store the result in the text file.

## Matrix multiplication using C programming

Before directly jumping into the source code, let’s understand the problem clearly. First, we will generate the two matrices into two different text files. Secondly, we will read the two matrices from the two different text files and store them in an array to perform matrix multiplication. Then finally we perform matrix multiplication and write the result in the text file.

### Generating the two matrices

We will use the “rand” function to generate the matrix element. You can also generate the matrix manually. Then we will save or write the data into matrixA.txt and matrixB.txt file.

rand(): It generates the random number in the range from 0 to RAND_MAX. You can have your own range of random numbers with some tricks with the rand function. For instance, if you want your random number to be from range 0 to 9, then use the modulus function along with rand(i.e rand()%10).

### Writing and reading matrix element

In order to write the matrix element to the text file, we will use the “fprintf” function. For the reading matrix element from the text file, we will use the “fscanf” function.

fprintf(): It writes formatted data to the file. The syntax is fprintf(FILE *ptr, const char *format, …).

fscanf(): It reads data from a file pointed by the file pointer. The syntax is fscanf(FILE *ptr, const char *format, …).

Some other functions in c that can be used to read and write the data to the files are as follows:

• getc() and putc()read and write a single character to the file.
• getw() and putw()read and write integer to the file.

The details of it can be found in the C FilesI/O: Create, Open, Read, Write and Close a File.

### Pseudocode for matrix multiplication

Input: The input to the program is matrix A and matrix B of different dimensions.

Output: Product of matrix A and matrix B into matrix C.

``````//arow and acol is the dimension of matrixA
//brow and bcol is the dimension of matrixB
Algorithm matrixMultiplication(matrixA, matrixB, arow, acol, brow, bcol){
for i=0 to arow-1 do
for j=0 to bcol-1 do
sum = 0
for k=0 to arow-1 do
sum = sum + matrixA[i][k] + matrixB[k][j]
matrix[i][j] = sum
}``````

This pseudocode contains the algorithm for matrix multiplication only. How to read and write data can be found in the source code below.

### Source code for matrix multiplication using the text file.

Input: We will generate the matrix A and matrix B and write it to text file matrixA.txt and matrixB.txt respectively. These two matrices text files will be the input to the main matrix multiplication.

Output: Compute the product of matrix A and matrix B then write the result in matrixC.txt file.

``````#include<stdio.h>
#include<stdlib.h>
int arow,acol,brow,bcol;
void generateMatrix(){
FILE *fptr;
//Creating the Matrix A
printf("Enter the row size for martix A(<1001):");
scanf("%d", &arow);
printf("Enter the column size for martix A(<1001):");
scanf("%d", &acol);
fptr = fopen("matrixA.txt", "w");
for(int i=0; i<arow; i++){
for(int j=0; j<acol; j++){
fprintf(fptr, "%d ", rand()%10);
}
fprintf(fptr, "\n");
}
fclose(fptr);

//Creating the Matrix B
printf("Enter the row size for martix B(<1001):");
scanf("%d", &brow);
printf("Enter the column size for martix B(<1001):");
scanf("%d", &bcol);
fptr = fopen("matrixB.txt", "w");
for(int i=0; i<brow; i++){
for(int j=0; j<bcol; j++){
fprintf(fptr, "%d ", rand()%10);
}
fprintf(fptr, "\n");
}
fclose(fptr);
}
void matrixMultiplication(){
FILE *fptr;
int matrixA[arow][acol], matrixB[brow][bcol], num;
//Accessing file a.txt and storing value in matrixA
fptr = fopen("matrixA.txt", "r");
for(int i=0; i<arow; i++){
for(int j=0; j<acol; j++){
fscanf(fptr, "%d", &num);
matrixA[i][j] = num;
}
}
fclose(fptr);

//Accessing file b.txt and storing the value in matrixB
fptr = fopen("matrixB.txt", "r");
for(int i=0 ; i<brow; i++){
for(int j=0; j<bcol; j++){
fscanf(fptr, "%d", &num);
matrixB[i][j] = num;
}
}
fclose(fptr);

//Matrix Multiplication
if(acol != brow){
printf("Matix Multiplication is not possible due to dimension conflicts\n");
}else{
fptr = fopen("matrixC.txt", "w");
for(int i=0; i<arow; i++){
for(int j=0; j<bcol; j++){
long long int sum = 0;
for(int k=0; k<acol; k++){
sum = sum + matrixA[i][k] * matrixB[k][j];
}
fprintf(fptr, "%lld ", sum);
}
fprintf(fptr, "\n");
}
fclose(fptr);
printf("Please check the file matrixC.txt for result\n");
}
}

int main(){
generateMatrix();
matrixMultiplication();
return 0;
}``````

This source code only works if you generate the matrix text file automatically as I did above. If you want to use the same source code with a manually generated matrix text file then you should have an idea of the dimension of the matrices and initialize the global variable arow, acol, brow, and bcol in the above code and you can remove the generateMatrix() function.

Alternatively, you can use the code given below to perform matrix multiplication with the manually generated matrix. You don’t have to specify the matrix dimension, the code will check the dimension and see if the two matrices can be multiplied and perform the task.

``````#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void matrixMultiplication(){
FILE *fptr;
int matrixA, matrixB, arow = 0, acol = 0, brow = 0, bcol = 0;
//Accessing file a.txt and storing value in matrixA
fptr = fopen("a.txt", "r");
char astr;
while(fgets(astr, sizeof(astr), fptr)){
int anum;
char *atoken;
acol = 0;
atoken = strtok(astr, " ");
while(atoken != NULL){
anum = atoi(atoken);
atoken = strtok(NULL, " ");
if((anum == 0) && (atoken == NULL)){
break;
}else{
matrixA[arow][acol] = anum;
acol += 1;
}
}
arow += 1;
}
fclose(fptr);

//Accessing file b.txt and storing the value in matrixB
fptr = fopen("b.txt", "r");
char bstr;
while(fgets(bstr, sizeof(bstr), fptr)){
int bnum;
char *btoken;
bcol = 0;
btoken = strtok(bstr, " ");
while(btoken != NULL){
bnum = atoi(btoken);
btoken = strtok(NULL, " ");
if((bnum == 0) && (btoken == NULL)){
break;
}else{
matrixB[brow][bcol] = bnum;
bcol += 1;
}
}
brow += 1;
}
fclose(fptr);

//Matrix Multiplication
if(acol != brow){
printf("Matix Multiplication is not possible due to dimension conflicts\n");
}else{
fptr = fopen("c.txt", "w");
for(int i=0; i<arow; i++){
for(int j=0; j<bcol; j++){
int sum = 0;
for(int k=0; k<acol; k++){
sum = sum + matrixA[i][k] * matrixB[k][j];
}
fprintf(fptr, "%d ", sum);
}
fprintf(fptr, "\n");
}
fclose(fptr);
printf("Please check the file c.txt for result\n");
}
}
int main(){
matrixMultiplication();
return 0;
}``````

The limitation to the above code is you can read the matrix element at a maximum of 1000 by 1000 dimensions. If you exceed the above dimension(1001 * 1001) then you will get the segmentation fault(core dump) error.

### Run time complexity of the matrix multiplication

Looking at the above code it might be clear that the run time of the above algorithm is O(n^3). Since there are three “for” loops iterating over the matrix to perform the matrix multiplication.

Therefore, the run time of the matrix multiplication is O(n^3).

## Conclusion

In this article, you have learned how to perform matrix multiplication. Especially in C programming language with a text file as matrix input to the program. The same algorithm can be implemented in any other programming language. Just some function names and syntax will be different. Also, you have learned how to read and write a file in C programming. If this article was helpful then do subscribe to our website to get the latest blog posts updates.

Scroll to Top