[mat64] Quick way to divide by certain row

46 views
Skip to first unread message

Bert Chang

unread,
Feb 20, 2015, 1:52:55 AM2/20/15
to gonu...@googlegroups.com
Hi,

I'm wondering when using mat64.Dense, how can I quickly divide the whole matrix by certain row?

For example, I have a matrix

[10, 6]
[20, 18]
[35, 60]
[5, 3]

and I want to divide the first column by 5, and the second column by 3.
I've checked MulElem, which seems to require same shape of matrix ..

Or I can only use for loop to do it myself?

Thanks.

Dan Kortschak

unread,
Feb 20, 2015, 2:22:15 AM2/20/15
to Bert Chang, gonu...@googlegroups.com
I'd iterate taking a column view of each column and scale that view by your column factor.

untested:

v := []float64{.......}
_, c := m.Dims()
if len(v) != c {
panic(mat64.ErrShape)
}
for j, f := range v {
vec := m.ColView(j).RawVector()
for i := 0; i < len(vec.Data); i+= vec.Inc {
vec.Data[i] *= f
}
}

If Vector had a Scale method you could use that. It doesn't (it would essentially be the inner for loop). Feel free to file an issue for that and we will consider adding it.

Dan Kortschak

unread,
Feb 20, 2015, 2:33:03 AM2/20/15
to Dan Kortschak, Bert Chang, gonu...@googlegroups.com
Alternatively, if you import (also untested)

v := []float64{.......}
r, c := m.Dims()
if len(v) != c {
panic(mat64.ErrShape)
}
for j, f := range v {
vec := m.ColView(j).RawVector()
blas64.Axpy(r, f, vec, vec)

Dan Kortschak

unread,
Feb 20, 2015, 2:44:47 AM2/20/15
to Bert Chang, gonu...@googlegroups.com
Sorry - this is clearly incorrect, and making it correct is not worth
the effort. Use the previous.

Dan Kortschak

unread,
Feb 20, 2015, 3:13:13 PM2/20/15
to Dan Kortschak, Bert Chang, gonu...@googlegroups.com
... or not...

v := []float64{.......}
r, c := m.Dims()
if len(v) != c {
panic(mat64.ErrShape)
}
for j, f := range v {
blas64.Scal(r, f, m.ColView(j).RawVector())

Chih-Wei Chang

unread,
Feb 20, 2015, 8:55:36 PM2/20/15
to Dan Kortschak, gonu...@googlegroups.com
Got it!
Thanks, this one is very clear and elegant. Is there any chance we can make it an mat64's API?
Thanks.

-- Chih-Wei (Bert)

於 2015年2月21日 於 上午4:13:12, Dan Kortschak (dan.ko...@adelaide.edu.au) 寫:

Dan Kortschak

unread,
Feb 20, 2015, 9:10:31 PM2/20/15
to Chih-Wei Chang, gonu...@googlegroups.com
On Sat, 2015-02-21 at 09:55 +0800, Chih-Wei Chang wrote:
> Thanks, this one is very clear and elegant. Is there any chance we can
> make it an mat64's API?

Please file an issue on gonum/matrix.

Jonathan Lawlor

unread,
Feb 21, 2015, 2:04:54 PM2/21/15
to gonu...@googlegroups.com, dan.ko...@adelaide.edu.au
You can also use Mul as follows:

package main

import (
"fmt"
)

func main() {
A := mat64.NewDense(4, 2, []float64{
10, 6,
20, 18,
35, 60,
5, 3,
})

b := []float64{5, 3}

B := mat64.NewDense(2, 2, nil)

for i, v := range b {
B.Set(i, i, 1/v)
}

A.Mul(A, B)

fmt.Println(A)
}
I don't know which way would be faster.
Reply all
Reply to author
Forward
0 new messages