Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying two 3x3 matrices in C

I am trying to multiply two 3x3 matrices. The first 2 numbers in the first and second row are the only correct answer. What am I doing wrong? Is the stuff I need declared in mult_matrices?

#include <stdio.h>

void mult_matrices(int a[][3], int b[][3], int result[][3]);
void print_matrix(int a[][3]);

int main()
{
    int p[3][3] = {{1, 2, 3},{4, 5, 6}, {7, 8, 9}};
    int q[3][3] = {{10, 11, 12}, {13, 14, 15}, {16, 17, 18}};
    int r[3][3];

    mult_matrices(p, q, r);
    print_matrix(r);
}

void mult_matrices(int a[][3], int b[][3], int result[][3])
{
    int i, j, k;
    for(i = 0; i < 3; i++)
    {
            for(j = 0; j < 3; j++)
            {
                    for(k = 0; k < 3; k++)
                    {
                            result[i][j] +=  a[i][k] *  b[k][j];
                    }
            }
    }
}

void print_matrix(int a[][3])
{
    int i, j;
    for (i = 0; i < 3; i++)
    {
            for(j = 0; j < 3; j++)
            {
                    printf("%d\t", a[i][j]);
            }
            printf("\n");
    }
 }
like image 838
james Avatar asked Apr 14 '11 22:04

james


People also ask

How to multiply two 3x3 matrices?

The result of a multiplication between two 3x3 matrices is going to be another matrix of the same order. The multiplication between matrices is done by multiplying each row of the first matrix with every column of the second matrix, and then adding the results, just like in the next example. Example 1: Multiply the following 3x3 matrices.

How to multiply two matrices in C?

C Multidimensional Arrays This program asks the user to enter the size (rows and columns) of two matrices. To multiply two matrices, the number of columns of the first matrix should be equal to the number of rows of the second matrix. The program below asks for the number of rows and columns of two matrices until the above condition is satisfied.

How to multiply two matrices using multi-dimensional arrays?

C Program to Multiply Two Matrices Using Multi-dimensional Arrays. 1 getMatrixElements () - to take matrix elements input from the user. 2 multiplyMatrices () - to multiply two matrices. 3 display () - to display the resultant matrix after multiplication.

How do you do matrix multiplication?

In matrix multiplication first matrix one row element is multiplied by second matrix all column elements. Let's try to understand the matrix multiplication of 2*2 and 3*3 matrices by the figure given below:


2 Answers

Make sure you initialize r to all zeros before you use it.

int r[3][3] = { 0 };
like image 107
Jeff Foster Avatar answered Nov 15 '22 04:11

Jeff Foster


Looks like you're not initializing your result matrix.

i.e. Change:

int r[3][3];

to

int r[3][3] ={{0,0,0},{0,0,0},{0,0,0}};
like image 28
yan Avatar answered Nov 15 '22 05:11

yan