1

If i have an array:

myzeros=scipy.zeros((c*pos,c*pos))  , c=0.1 , pos=100

and an array:

grid=scipy.ones((pos,pos))

How can i insert the zeros into the grid in random positions? The problem is with the dimensions.

I know that in 1d you can do:

myzeros=sc.zeros(c*pos) # array full of (zeros)
grid=sc.ones(pos)         # grid full of available positions(ones)
dist=sc.random.permutation(pos)[:c*pos] # distribute c*pos zeros in random
                                        # positions
grid[dist]=myzeros

I tried something similar but it doesn't work. I tried also: myzeros=sc.zeros(c*pos), but it still does not work.

1 Answer 1

3

There are several ways, but the easiest seems to be to first convert the 2D grid into a 1D grid and proceed as in the 1D case, then convert back to 2D:

c = 0.1
pos = 100
myzeros=scipy.zeros((c*pos,c*pos))
myzeros1D = myzeros.ravel()
grid=scipy.ones((pos,pos))
grid1D = grid.ravel()
dist=sc.random.permutation(pos*pos)[:c*pos*c*pos]
grid1D[dist]=myzeros1D
myzeros = myzeros1D.reshape((c*pos,c*pos))
grid = grid1D.reshape((pos, pos))

EDIT: to answer your comment: if you only want a part of the myzeros to go into the grid array, you have to make the dist array smaller. Example:

dist = scipy.random.permutation(pos*pos)[:c*pos]
grid1D[dist] = myzeros1D[:c*pos]

And I hope you are aware, that this last line can be written as

grid1D[dist] = 0

if you really only want to set those elements to a single instead of using the elements from another array.

Sign up to request clarification or add additional context in comments.

4 Comments

:Hello, when i run the last command it gives me "grid = grid1D.reshape((cpos, cpos))" ..Any ideas?Thanks!
Hi, I'm not sure what you mean by that, but I have had an error in the last line. Maybe you just forgot to press enter ofter the last line?
:I had a typo error.It works.But the problem is that i want to insert cpos zeros into the grid=scipy.ones((pos,pos)).With the above ,it inserts the number of shape of the myzeros array (cpos cpos) into the grid.I can't figure a way to do that!
:Exactly what i want!Thanks a lot.Also,it doesn't need to be created the myzeros=scipy.zeros((cpos,cpos)).It can be done with 1D myzeros.(this goes about my second question).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.