jeff
jeff

Reputation: 11

how do multiply different sized matrices in c

I'm looking for a way to multiply a 2x1 and a 2x2 matrix together but my code doesn't work almost every time and even when it does work I have to put the numbers into the code. It doesn't wok if i try asking for the numbers when I run the code

Here is my code so far:

#include <stdio.h>
#include <stdlib.h>

int main(void)  
{  
  unsigned int a[1][2],b[2][2],c[2][1], i=0, j=0, k=0;  
  printf("-=Program to Multiply two Matrices=-");  


//--------------------------------------------------------------------  

 printf("\nEnter the values of Matrix A: \n");  

  for(i=0;i<1;i++)  
    {  
      for(j=0;j<2;j++)  
        {  
         // printf("\n"); 
          scanf("%d",&a[i][j]);  
        }  
     }  
   printf("\nMatrix A: ");  
   for(i=0;i<1;i++)  
    {  
      printf("\n");  
      for(j=0;j<2;j++)  
        {  
          printf(" ");  
          printf("%d",a[i][j]);  
        }  
     }  
//----------------------------------------------------  

printf("\nEnter the values of Matrix B: \n");  
  for(i=0;i<2;i++)  
    {  
      for(j=0;j<2;j++)  
        {  
         // printf("\n");  
          scanf("%d",&b[i][j]);  
        }  
     }  
   printf("\nMatrix B: ");  
   for(i=0;i<2;i++)  
    {  
      printf("\n");  
      for(j=0;j<2;j++)  
        {  
          printf(" ");  
          printf("%d",b[i][j]);  
        }  
     }  

//--------------------------------------------------------  

  printf("\n\nMultiplication of matrices A and B is : \n\n");  
  for(i=0;i<2;i++)  
   {  
     for(j=0;j<2;j++)  
       {  
          c[i][j]=0;  
          for(k=0;k<1;k++)  
            {  
        c[i][j]=c[i][j]+(a[i][k]*b[k][j]);  
            }  
       }  
   }  
  printf("\nMatrix C (Resultant Matrix): ");  
    for(i=0;i<2;i++)  
    {  
      printf("\n");  
      for(j=0;j<1;j++)  
        {  
          printf(" ");  
          printf("%d",c[i][j]);  
        }  
     }  
printf("\n");  
  return 0;  
}  

Upvotes: 0

Views: 4328

Answers (2)

Muthusamy
Muthusamy

Reputation: 56

as long as matrix multiplication is concerned,it is possible only if the number of columns of the first matrix matches with the number of rows in second matrix,so there is no use of doing this and the entire concept is wrong

Upvotes: 0

Javed Akram
Javed Akram

Reputation: 15344

Basic Concept of multiplication of matrices is 1st Matrix Column must be equal to Row of 2nd matrix

Example:

//valid since column of A is equal to row of B i.e. 2

Matrix A = 1 X 2
Matrix B = 2 X 2

//Invalid (Your Case)
Matrix A = 2 X 1
Matrix B = 2 X 2

Matrix Multiplication image

Upvotes: 1

Related Questions