Skip to content

Commit f730c87

Browse files
committed
scalar multiplication added
1 parent ff1fe31 commit f730c87

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

ADT/miscellaneous/matrix.cpp

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ class matrix {
100100
matrix<DATA> operator+(matrix const& );
101101
matrix<DATA> operator-(matrix const& );
102102
matrix<DATA> operator&(matrix const& ); //matrix multiply
103+
matrix<DATA> operator*(DATA scalar); //scalar multiplication (scalar on rhs of *)
103104

104105
//transpose operator
105106
matrix<DATA> operator!();
@@ -132,6 +133,19 @@ matrix<DATA> eye(int n) {
132133

133134
///// MATRIX OPERATIONS DEFINITIONS START HERE ////
134135

136+
template<typename DATA>
137+
matrix<DATA> matrix<DATA>::operator*(DATA scalar) {
138+
matrix<DATA> m(this->row, this->col);
139+
140+
for(int i=0; i<this->row; i++)
141+
for(int j=0; j<this->col; j++) {
142+
int temp = *(val + (this->col)*i + j);
143+
*(m.val + i*m.col + j) = scalar * temp;
144+
}
145+
146+
return m;
147+
}
148+
135149

136150
template<typename DATA>
137151
matrix<DATA> matrix<DATA>::operator&(matrix const &obj) {
@@ -271,15 +285,17 @@ void init2dArray(int *array, int size_0, int size_1) {
271285
int main() {
272286

273287
int row=2,
274-
col=3;
288+
col=3,
289+
row2=3,
290+
col2=2;
275291

276292
int *array1 = new int[row*col];
277-
int *array2 = new int[row*col];
293+
int *array2 = new int[row2*col2];
278294
init2dArray(array1, row, col); // 2x3 array
279-
init2dArray(array2, row, col); // 3x2 array
295+
init2dArray(array2, row2, col2); // 3x2 array
280296

281297
matrix<int> m1(array1, row, col); //2x3 matrix
282-
matrix<int> m2(array2, row, col); //3x2 matrix
298+
matrix<int> m2(array2, row2, col2); //3x2 matrix
283299

284300
matrix<int> m3 = m1 & m2;
285301

@@ -289,12 +305,15 @@ int main() {
289305
cout<<"\nMatrix Multiplication Result:-\n";
290306
m3.display();
291307

308+
matrix<int> m4 = m3*2;
309+
m4.display();
310+
292311
delete array1;
293312
delete array2;
294313
array1 = NULL;
295314
array2 = NULL;
296315

297-
return 0;
316+
return 1;
298317
}
299318

300319

0 commit comments

Comments
 (0)