Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matrix and vector multiplication

Suppose we have 3*3 matrix like this:

1 3  4
2 6 8
9 0 12

And some vector like this:

1   2   3 

My question is: how to implement it so that I could multiply one by another? I have example code:

#include <cstdlib>
#include <math.h>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int a[3][3]={{ 2,4,3},{1,5,7},{0,2,3}};
    int b[]={2,5,6};
    int c[3];

    for (int i=0;i<3;i++){
         c[i]=0;
    }

    for (int i=0;i<3;i++){
        for (int j=0;j<3;j++){
            c[i]+=( a[i][j]*b[j]);
        }
    }

    for (int i=0;i<3;i++){
        cout<<a[i]<<"  "<<endl;
    }

    system("PAUSE");
    return EXIT_SUCCESS;
}

The result I got is:

0x22ff10
0x22ff1c
0x22ff28

2 Answers

Change:

 for (int i=0;i<3;i++){
      cout<<a[i]<<"  "<<endl;

to:

 for (int i=0;i<3;i++){
      cout<<c[i]<<"  "<<endl;
like image 107
Paul R Avatar answered Apr 18 '26 19:04

Paul R


I think you want to be printing c[i], not a[i], in your last loop.

like image 28
Carl Norum Avatar answered Apr 18 '26 20:04

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!