matrix functions.

i need help defining a matrix class for operator *= . i have already defined *, +, += and the other operator but i cant get *= right.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Matrix{

public:
Matrix(int a1, int b1, int c1, int d1);

//member function operator declaration for *=
Matrix& operator*=(const Matrix& s);

private:
int a, b, c, d;
};

Matrix& Matrix::operator*=(const Matrix& s){
 
 
a *= (s.a) +(b *s.c);
b *= (s.d) +(a *s.b);
c *= (s.a) +(d *s.c);
d *= (s.d) +(c *s.b);

return (*this);
}

i know its wrong because it output the wrong values.
this is the code for the * operator.
1
2
3
4
5
6
7
8
9
10
11
//friend operator declaration for *
//public:
friend Matrix operator *(const Matrix& r, const Matrix& s);

Matrix operator*(const Matrix& r, const Matrix& s){
int a= ((r.a*s.a)+(r.b*s.c));
int b= ((r.a*s.b)+ (r.b*s.d));
int c= ((r.c*s.a)+(r.d*s.c));
int d= ((r.c*s.b)+ (r.d*s.d));
return Matrix(a, b, c, d);
}

i hope someone is able to help me
This
 
a *= (s.a) +(b *s.c);

Is short hand for this:
 
a = a * ( (s.a) + (b * s.c) );


Work the right hand side out algebraically. Is this really the computation you intended?
Last edited on
nope.. thats my problem.. i wanted to compute this
a= ((r.a*s.a)+(r.b*s.c));
using *= operator.

ex. with the + operator i did this.
1
2
int a = r.a + s.a; //for +
a+= s.a; //for += 


This
a += s.a does mean this
a = a + s.a

So you were good there.

For the matrix multiplication, as you know already, you need the sum of two products of different terms. The multiply and assign (*=) simply can't do that for you. You'll just have to code your *= operator without it.
How would i do that? Can u give me any example?
An operator is simply a function. If you have already written an operator for multiplication, you should already know what need to take place in a multiply and assign operator.

You already have an example:


this is the code for the * operator.
1
2
3
4
5
6
7
8
9
10
11
//friend operator declaration for *
//public:
friend Matrix operator *(const Matrix& r, const Matrix& s);

Matrix operator*(const Matrix& r, const Matrix& s){
int a= ((r.a*s.a)+(r.b*s.c));
int b= ((r.a*s.b)+ (r.b*s.d));
int c= ((r.c*s.a)+(r.d*s.c));
int d= ((r.c*s.b)+ (r.d*s.d));
return Matrix(a, b, c, d);
}



You can implement the *= operator by modify this function, or you can do the smart thing, and take advantage of the fact that you have already written a multiplication operator and use it in your multiply and assign operator.

You need to think critically about what EXACTLY your operator is required to do, AND about why you are overloading operators in the first place.

Anyone who would do this for you will be holding you back.
Thnaks alot :)
Topic archived. No new replies allowed.