[Tutor] How to sum weighted matrices
Rafael Durán Castañeda
rafadurancastaneda at gmail.com
Thu Mar 10 16:53:49 CET 2011
Numpy apart, you can use lists and loops:
>>> matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
>>> matrix2 = [[3, 2, 1],
[6, 5, 4],
[9, 8, 7]]
>>> result = []
>>> w = [1, 2]
>>> for x in range(len(matrix)):
row = []
for y in range(len(matrix[x])):
row.append((w[0]*matrix[x][y])+(w[1]*matrix2[x][y]))
result.append(row)
>>> result
[[7, 6, 5], [16, 15, 14], [25, 24, 23]]
>>>
But I think this isn't pythonic way, so maybe someone else can help you
2011/3/7 shu wei <mailshuwei at gmail.com>
> Hello all,
>
> I am new to python and numpy.
> My question is how to sum up N weighted matrices.
> For example w=[1,2] (N=2 case)
> m1=[1 2 3,
> 3 4 5]
>
> m2=[3 4 5,
> 4 5 6]
> I want to get a matrix Y=w[1]*m1+w[2]*m2 by using a loop.
>
> My original problem is like this
> X=[1 2 3,
> 3 4 5,
> 4 5 6]
>
> a1=[1 2 3] 1st row of X
> m1=a1'*a1 a matirx
> a2=[3 4 5] 2nd row of X
> m2=a2'*a2
> a3=[ 4 5 6] 3rd row of X
> m3=a3'*a3
>
> I want to get Y1=w[1]*m1+w[2]*m2
> Y2=w[1]*m2+w[2]*m3
> So basically it is rolling and to sum up the weighted matries
> I have a big X, the rolling window is relatively small.
>
> I tried to use
>
> sq=np.array([x[i].reshape(-1,1)*x[i] for i in np.arange(0,len(x)]) #
> s=len(x)
> m=np.array([sq[i:i+t] for i in np.arange(0,s-t+1)]) # t is the len(w)
>
> then I was stuck, I tried to use a loop somethig like
> Y=np.array([np.sum(w[i]*m[j,i],axis=0) for i in np.arange(0,t)] )
> Any suggestion is welcome.
>
> sue
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110310/d325ef31/attachment.html>
More information about the Tutor
mailing list