File tree Expand file tree Collapse file tree 1 file changed +16
-7
lines changed
Expand file tree Collapse file tree 1 file changed +16
-7
lines changed Original file line number Diff line number Diff line change @@ -142,15 +142,24 @@ public function multiply(self $matrix): self
142142 throw new InvalidArgumentException ('Inconsistent matrix supplied ' );
143143 }
144144
145+ $ array1 = $ this ->toArray ();
146+ $ array2 = $ matrix ->toArray ();
147+ $ colCount = $ matrix ->columns ;
148+
149+ /*
150+ - To speed-up multiplication, we need to avoid use of array index operator [ ] as much as possible( See #255 for details)
151+ - A combination of "foreach" and "array_column" works much faster then accessing the array via index operator
152+ */
145153 $ product = [];
146- $ multiplier = $ matrix ->toArray ();
147- for ($ i = 0 ; $ i < $ this ->rows ; ++$ i ) {
148- $ columns = $ matrix ->getColumns ();
149- for ($ j = 0 ; $ j < $ columns ; ++$ j ) {
150- $ product [$ i ][$ j ] = 0 ;
151- for ($ k = 0 ; $ k < $ this ->columns ; ++$ k ) {
152- $ product [$ i ][$ j ] += $ this ->matrix [$ i ][$ k ] * $ multiplier [$ k ][$ j ];
154+ foreach ($ array1 as $ row => $ rowData ) {
155+ for ($ col = 0 ; $ col < $ colCount ; ++$ col ) {
156+ $ columnData = array_column ($ array2 , $ col );
157+ $ sum = 0 ;
158+ foreach ($ rowData as $ key => $ valueData ) {
159+ $ sum += $ valueData * $ columnData [$ key ];
153160 }
161+
162+ $ product [$ row ][$ col ] = $ sum ;
154163 }
155164 }
156165
You can’t perform that action at this time.
0 commit comments