LabAssignment 1c (35 points). Write a C function to do matrix (2D) multiplicatio
ID: 3715818 • Letter: L
Question
LabAssignment 1c (35 points). Write a C function to do matrix (2D) multiplication calculation. You can name the function like mat_multiply0. The function takes two arguments, A and B, which both are int matrix. The function returns a matrix C, which is the multiplication of A and B. Row and columns numbers of A and B are not fixed. Search online for matrix multiplication rules, if you are not sure. You can create two small (rows and column numbers are between 3-5) matrices in your main function to test mat_multiply0 Tip: you should check the dimension match in the beginning of your function and print out error message, if the dimensions of A and B are not matched for multiplication.Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
void mat_multiply(int A[][10],int B[][10], int r1,int c1, int r2, int c2 )
{
int i,j,k;
int C[10][10];
for(i=0;i<r1;i++) //Multiplication starts here
{
for(j=0;j<c2;j++)
{
C[i][j]=0;
for(k=0;k<r2;k++)
C[i][j] += A[i][k] * B[k][j];
}
}
printf(" The result of multiplication of matrices A & B is ");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
printf("%5d",C[i][j]);
printf(" ");
}
}
int main()
{
int r1,c1,r2,c2; //matrix dimensions for A and B
int i,j,k;
printf(" enter first matrix rows & columns ");
scanf("%d%d",&r1,&c1);
printf(" enter second matrix rows & columns ");
scanf("%d%d",&r2,&c2);
while(c1 != r2) //loop till the matrix multiplication is possible
{
printf(" Matrix multiplication is not possible ");
printf(" enter first matrix rows & columns ");
scanf("%d%d",&r1,&c1);
printf(" enter second matrix rows & columns ");
scanf("%d%d",&r2,&c2);
}
int A[r1][c1],B[r2][c2];
printf(" Enter first matrix data elements ");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
{
printf("A[%d][%d] = ",i,j);
scanf("%d",&A[i][j]);
}
printf(" Enter second matrix data elements ");
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
{
printf("B[%d][%d] = ",i,j);
scanf("%d",&B[i][j]);
}
mat_multiply(A,B,r1,c1,r2,c2);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.