[Numpy-discussion] Matrix operation.

Shailendra shailendra.vikas@gmail....
Fri Apr 2 09:43:40 CDT 2010


>>> A=[[1,1,0],
... [1,0,0],
... [0,0,1]]
>>> X=[2,9,10,3]
>>> import numpy
>>> A=numpy.asarray(A)
>>> X=numpy.asarray(X)
>>> A
array([[1, 1, 0],
       [1, 0, 0],
       [0, 0, 1]])
>>> X
array([ 2,  9, 10,  3])
>>> non_zero=numpy.nonzero(A)
>>> non_zero
(array([0, 0, 1, 2]), array([0, 1, 0, 2]))
>>> A[non_zero]
array([1, 1, 1, 1])
>>> A[non_zero]=X
>>> A
array([[ 2,  9,  0],
       [10,  0,  0],
       [ 0,  0,  3]])

Thanks,
Shailendra

On Fri, Apr 2, 2010 at 10:35 AM, gerardob <gberbeglia@gmail.com> wrote:
>
> Let A be a square matrix of 0's and 1's, and let X be a one dimesional
> vector.
> The length of X is equal to the number of 1's that A has.
> I would like to produce a new matrix B by traversing the matrix A row by row
> and:
> 1- whenever i find a 0, set B in that position to zero.
> 2- whenever i find a 1, set B in that position with the ith value of X
> (where i represents the ith time i found a 1).
>
> Example.
> input:
> A=[[1,1,0],
> [1,0,0],
> [0,0,1]]
>
> X=[2,9,10,3]
>
> Output:
> B =[[2,9,0],
>   [10,0,0],
>   [0,0,3]]
>
> Which is an efficient way to accomplish this using numpy?
>
> Thanks.
> --
> View this message in context: http://old.nabble.com/Matrix-operation.-tp28119663p28119663.html
> Sent from the Numpy-discussion mailing list archive at Nabble.com.
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>


More information about the NumPy-Discussion mailing list