[Numpy-discussion] more complex matrix operation
josef.pktd at gmail.com
josef.pktd at gmail.com
Mon Mar 15 11:06:37 EDT 2010
On Mon, Mar 15, 2010 at 9:58 AM, Gerardo Berbeglia <gberbeglia at gmail.com> wrote:
> I have another matrix operations which seems a little more complicated.
>
> Let A be an n x n matrix and let S be a subset of {0,...,n-1}. Assume
> S is represented by a binary vector s, with a 1 at the index i if i is
> in S. (e.g. if S={0,3} then s = [1,0,0,1])
>
> I would like to have an efficient way to compute the function B = f
> (A,S) characterized as follows:
>
> - For each column i such that i is in S, then the column i of B is
> equal to the column i of A.
>
> - For each column i such that i is NOT in S, then the column i of B is
> equal to the ith column of the n x n identity matrix.
>
> Example. n=4.
> A = [[2,2,2,2],[3,3,3,3][4,4,4,4][5,5,5,5]]
> S = {0,2} => s=[1,0,1,0]
>
> f(A,S) = [[2,2,2,2],[0,1,0,0],[4,4,4,4],[0,0,0,1]]
here you have the rows changed ?
>
> Which is the best way to compute f?
similar pattern as before.
I think using boolean array as selector might be the easiest
>>> s=np.array([1,0,1,0],bool)
>>> s
array([ True, False, True, False], dtype=bool)
>>> B = np.eye(n,dtype=int)
>>> A
array([[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
[5, 5, 5, 5]])
>>> B[:,s] = A[:,s]
>>> B
array([[2, 0, 2, 0],
[3, 1, 3, 0],
[4, 0, 4, 0],
[5, 0, 5, 1]])
Josef
>
> Thanks again.
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
More information about the NumPy-Discussion
mailing list