Skip to content Skip to sidebar Skip to footer

Reading a Matrix From a Text File in C

How to perform matrix multiplication in C programming linguistic communication using text file? If this is the question that brought y'all to this website and so you are in right identify. In this article, you volition larn 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 straight jumping into the source code, let'south understand the problem clearly. First, we will generate the ii matrices into 2 different text files. Secondly, we will read the two matrices from the two dissimilar text files and store them in an assortment to perform matrix multiplication. So finally we perform matrix multiplication and write the result in the text file.

Generating the two matrices

We volition use the "rand" role to generate the matrix element. You lot tin can too generate the matrix manually. Then we will save or write the information into matrixA.txt and matrixB.txt file.

rand(): It generates the random number in the range from 0 to RAND_MAX. Y'all can have your own range of random numbers with some tricks with the rand part. For example, if yous want your random number to be from range 0 to nine, then use the modulus function along with rand(i.e rand()%ten).

Writing and reading matrix chemical element

In order to write the matrix chemical element to the text file, we will use the "fprintf" part. For the reading matrix element from the text file, we will use the "fscanf" role.

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 arrow. The syntax is fscanf(FILE *ptr, const char *format, …).

Another functions in c that tin exist used to read and write the data to the files are as follows:

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

The details of information technology 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 dissimilar 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-i do             sum = 0             for g=0 to arow-ane do                 sum = sum + matrixA[i][k] + matrixB[chiliad][j]             matrix[i][j] = sum }              

This pseudocode contains the algorithm for matrix multiplication only. How to read and write data tin can be plant in the source lawmaking beneath.

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 exist the input to the main matrix multiplication.

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

                #include<stdio.h> #include<stdlib.h> int arow,acol,forehead,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", "westward"); 	for(int i=0; i<arow; i++){ 		for(int j=0; j<acol; j++){ 			fprintf(fptr, "%d ", rand()%ten); 		} 		fprintf(fptr, "\due north"); 	} 	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, "\due north"); 	} 	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\due north"); 	 }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 grand=0; one thousand<acol; one thousand++){ 	 				sum = sum + matrixA[i][k] * matrixB[thou][j]; 	 			} 	 			fprintf(fptr, "%lld ", sum); 	 		} 	 		fprintf(fptr, "\n"); 	 	} 	 	fclose(fptr); 	 	printf("Please cheque the file matrixC.txt for upshot\n"); 	 }	 }  int main(){ 	generateMatrix(); 	matrixMultiplication(); 	return 0; }              

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

Alternatively, you can utilise the code given below to perform matrix multiplication with the manually generated matrix. You don't accept to specify the matrix dimension, the code volition check the dimension and see if the 2 matrices can be multiplied and perform the task.

                #include<stdio.h> #include<stdlib.h> #include<string.h> void matrixMultiplication(){ 	FILE *fptr; 	int matrixA[1001][1001], matrixB[1001][1001], arow = 0, acol = 0, brow = 0, bcol = 0; 	//Accessing file a.txt and storing value in matrixA 	fptr = fopen("a.txt", "r"); 	char astr[2002]; 	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 == Aught)){ 				break; 			}else{ 				matrixA[arow][acol] = anum; 				acol += one; 			}			 		} 		arow += 1;		 	} 	fclose(fptr);  	//Accessing file b.txt and storing the value in matrixB 	fptr = fopen("b.txt", "r"); 	char bstr[2002]; 	while(fgets(bstr, sizeof(bstr), fptr)){ 		int bnum; 		char *btoken; 		bcol = 0; 		btoken = strtok(bstr, " "); 		while(btoken != Zilch){ 			bnum = atoi(btoken); 			btoken = strtok(NULL, " "); 			if((bnum == 0) && (btoken == NULL)){ 				intermission; 			}else{ 				matrixB[brow][bcol] = bnum; 				bcol += 1;			 			} 		} 		forehead += 1; 	} 	fclose(fptr);  	//Matrix Multiplication 	 if(acol != brow){ 	 	printf("Matix Multiplication is not possible due to dimension conflicts\northward"); 	 }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 yard=0; thou<acol; grand++){ 	 				sum = sum + matrixA[i][yard] * matrixB[thou][j]; 	 			} 	 			fprintf(fptr, "%d ", sum); 	 		} 	 		fprintf(fptr, "\northward"); 	 	} 	 	fclose(fptr); 	 	printf("Delight check the file c.txt for consequence\north"); 	 } } int main(){ 	matrixMultiplication(); 	return 0; }              

The limitation to the above code is you can read the matrix element at a maximum of g by 1000 dimensions. If you exceed the higher up dimension(1001 * 1001) and then you will get the partitioning mistake(cadre dump) error.

Run fourth dimension complexity of the matrix multiplication

Looking at the higher up code it might be articulate that the run time of the above algorithm is O(n^iii). Since in that location are three "for" loops iterating over the matrix to perform the matrix multiplication.

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

Conclusion

In this article, y'all have learned how to perform matrix multiplication. Particularly in C programming linguistic communication with a text file as matrix input to the program. The same algorithm can be implemented in any other programming linguistic communication. Just some role names and syntax will be different. Besides, you accept 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.

fernandesabour1978.blogspot.com

Source: https://learn.drukinfotech.com/matrix-multiplication-using-text-file-in-c/

Отправить комментарий for "Reading a Matrix From a Text File in C"