A matrix problem. Please help!
Carl
phleum_nospam at chello.se
Wed Feb 4 15:23:19 EST 2004
Peter Otten wrote:
> Carl wrote:
>
>> I have the following matrix that I want to transform:
>>
>> import random
>> import Numeric as N
>> ru = []
>> for i in range(25):
>> ru.append(int(random.uniform(0, 2)))
>> ru = N.reshape(ru, (5, 5))
>>
>>>>> ru
>> array([[1, 0, 1, 1, 1],
>> [0, 1, 1, 1, 0],
>> [1, 1, 0, 0, 1],
>> [0, 1, 0, 0, 1],
>> [1, 1, 0, 1, 1]])
>>
>> Trailing numbers (ie, from left to right) after the first encounter of a
>> "1" for all rows should equal "0".
>>
>> Thus, I want this:
>>
>>>>> ru
>> array([[1, 0, 0, 0, 0],
>> [0, 1, 0, 0, 0],
>> [1, 0, 0, 0, 0],
>> [0, 1, 0, 0, 0],
>> [1, 0, 0, 0, 0]])
>>
>> Does anyone have a suggestion of a fast and easy way to accomplish the
>> above?
>>
>> Carl
>
> (Disclaimer: Numeric newbie code)
>
>>>> import random
>>>> import Numeric
>>>> import itertools
>>>> def oneone():
> ... while 1:
> ... r = int(random.uniform(0, 2))
> ... yield r
> ... if r: break
> ... for r in itertools.repeat(0):
> ... yield r
> ...
>>>> ru = Numeric.array([[x for x,y in itertools.izip(oneone(), range(5))]
> for z in range(5)])
>>>> ru
> array([[0, 0, 1, 0, 0],
> [0, 0, 0, 1, 0],
> [1, 0, 0, 0, 0],
> [0, 0, 0, 1, 0],
> [0, 0, 1, 0, 0]])
>>>>
>
> Or, more seriously, i. e. assuming that you have no influence on the
> initial matrix:
>
>>>> r
> array([[1, 1, 1],
> [0, 1, 1],
> [0, 0, 1]])
>>>> for i in r:
> ... for k in Numeric.nonzero(i)[1:]:
> ... i[k] = 0
> ...
>>>> r
> array([[1, 0, 0],
> [0, 1, 0],
> [0, 0, 1]])
>
> Peter
Thanks Peter,
This:
for i in ru:
for k in N.nonzero(i)[1:]:
i[k] = 0
works very nice, but I'm a little worried about performance problem, since
the matrix ru is typically of size 10,000 to 100,000 rows by 10 to 60
columns.
I have tried to figure out how to do it without loops, but have not managed
to do that yet.
Carl
More information about the Python-list
mailing list