Assign values to a matrix in Python - python

I have wrote this piece of code and need to generate a matrix and save it. But, when assigning the matrix values, it says "KeyError: 0"!! Anybody has an idea what is the reason? thanks
import numpy as np
l=5; x=0; z=5; y=np.arange(0,5,0.5)
positions = { (i,j):0 for i in range(l) for j in range(2)}
for i in range(l):
positions[i][0]=x
positions[i][1]=y[i]
positions[i][2]=z

I am not sure what is the shape of matrix you need but assuming something like:
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
then code:
import numpy as np
l=5; x=0; z=5; y=np.arange(0,5,0.5)
positions = [[0 for j in range(3)] for i in range(l)]
print(positions)
for i in range(l):
positions[i][0]=x
positions[i][1]=y[i]
positions[i][2]=z

It's how you structured your keys, it should be a tuple instead of something array like
import numpy as np
l=5; x=0; z=5; y=np.arange(0,5,0.5)
positions = { (i,j):0 for i in range(l) for j in range(2)}
for i in range(l):
positions[(i, 0)] = x
positions[(i, 1)] = y[i]
positions[(i, 2)] = z

Related

Python convert nested array to cython c array

I want to convert array of array which have default value of zeros in each array. The reason to do this is that I want to convert a high computing algorithm from python to cython to speed up computation more. The code for array is like this for python:
self.v = [[0 for i in range(self.D)] for j in range(self.NP)] #velocity
self.Sol = [[0 for i in range(self.D)] for j in range(self.NP)]
self.D and self.NP could be any integer values. The format of the sample data in python is like this, for self.D=4 and self.NP=3:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Python 2D Array Unexpected Overwrite

I am simplifying a use case, but given a 2D array I'd like to overwrite the first column with the value of i at each column. However instead of overwriting a single cell, it is overwriting the entire column at every step.
array = [[0,0,0], [0,0,0], [[0,0,0]]
for i in range(3):
array[i][0] = i+1
print(array)
Expected Output:
[[1,0,0], [0,0,0], [[0,0,0]]
[[1,0,0], [2,0,0], [[0,0,0]]
[[1,0,0], [2,0,0], [[3,0,0]]
Actual Output:
[[1,0,0], [1,0,0], [1,0,0]]
[[2,0,0], [2,0,0], [2,0,0]]
[[3,0,0], [3,0,0], [3,0,0]]
I suspect calling range() is somehow effecting this but I do not know why. Please help explain why accessing a single cell overwrites the entire column each time!
I tried your solution (minus the extra square bracket on the first line) and I have your expected result. So you may have to think about how about you build your input array.
input_array = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(3):
input_array[i][0] = i + 1
print(input_array)
Another solution with the same answer:
input_array = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for (i, line) in enumerate(input_array):
line[0] = i + 1
print(input_array)

How to used np.where to return a list of tuples with all positions in a 2D numpy array equal to zero?

I am learning about numpy and as an exercise I have to create a function possibilities that has as an input a numpy 2D array with integers and must return a list of tuples where the values are zeros. I've been told that numpy has a function where that can help. I read the docs but couldn't understand it at least not for this task so I had to do it with for loops like this:
def possibilities(board):
not_occupied = []
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
not_occupied.append((i,j))
return not_occupied
Board is somthing like this:
board = [[1,2,0],[0,0,1],[2,0,1]]
How I could use numpy where to do that instead?
You could use argwhere:
import numpy as np
board = [[1, 2, 0],
[0, 0, 1],
[2, 0, 1]]
result = np.argwhere(np.array(board) == 0).tolist()
Output
[[0, 2], [1, 0], [1, 1], [2, 1]]
If the coordinates must be tuples you could do:
result = [tuple(coord) for coord in np.argwhere(np.array(board) == 0).tolist()]
Output
[(0, 2), (1, 0), (1, 1), (2, 1)]
You could use the zip function to re-pair the result of where
list(zip(*np.where(board == 0)))

Creating 2d histogram from 2d numpy array

I have a numpy array like this:
[[[0,0,0], [1,0,0], ..., [1919,0,0]],
[[0,1,0], [1,1,0], ..., [1919,1,0]],
...,
[[0,1019,0], [1,1019,0], ..., [1919,1019,0]]]
To create I use function (thanks to #Divakar and #unutbu for helping in other question):
def indices_zero_grid(m,n):
I,J = np.ogrid[:m,:n]
out = np.zeros((m,n,3), dtype=int)
out[...,0] = I
out[...,1] = J
return out
I can access this array by command:
>>> out = indices_zero_grid(3,2)
>>> out
array([[[0, 0, 0],
[0, 1, 0]],
[[1, 0, 0],
[1, 1, 0]],
[[2, 0, 0],
[2, 1, 0]]])
>>> out[1,1]
array([1, 1, 0])
Now I wanted to plot 2d histogram where (x,y) (out[(x,y]) is the coordinates and the third value is number of occurrences. I've tried using normal matplotlib plot, but I have so many values for each coordinates (I need 1920x1080) that program needs too much memory.
If I understand correctly, you want an image of size 1920x1080 which colors the pixel at coordinate (x, y) according to the value of out[x, y].
In that case, you could use
import numpy as np
import matplotlib.pyplot as plt
def indices_zero_grid(m,n):
I,J = np.ogrid[:m,:n]
out = np.zeros((m,n,3), dtype=int)
out[...,0] = I
out[...,1] = J
return out
h, w = 1920, 1080
out = indices_zero_grid(h, w)
out[..., 2] = np.random.randint(256, size=(h, w))
plt.imshow(out[..., 2])
plt.show()
which yields
Notice that the other two "columns", out[..., 0] and out[..., 1] are not used. This suggests that indices_zero_grid is not really needed here.
plt.imshow can accept an array of shape (1920, 1080). This array has a scalar value at each location in the array. The structure of the array tells imshow where to color each cell. Unlike a scatter plot, you don't need to generate the coordinates yourself.

Adding values to a matrix with a for loop in python

My intention with this program was to get a 4x4 matrix with certain values, but for some reason the loop is putting everything into the same row/column... What is off about my code?
def matrixH0(k):
H0=[]
print H0
for m in range (0,k):
for n in range (0,k):
if abs(m-n)==1:
H0.append(math.sqrt(n+m+1)/2.)
else:
H0.append(0)
print H0
This is my output:
[0,
0.7071067811865476,
0,
0,
0.7071067811865476,
0,
1.0,
0,
0,
1.0,
0,
1.224744871391589,
0,
0,
1.224744871391589,
0]
Append rows to H0, append values to rows:
import math
import pprint
def matrixH0(k):
H0 = []
for m in range(k):
# create a new row
row = []
for n in range(k):
if abs(m-n)==1:
row.append(math.sqrt(n+m+1)/2.)
else:
row.append(0)
H0.append(row)
return H0
pprint.pprint(matrixH0(4))
yields
[[0, 0.7071067811865476, 0, 0],
[0.7071067811865476, 0, 1.0, 0],
[0, 1.0, 0, 1.224744871391589],
[0, 0, 1.224744871391589, 0]]
By the way, matrixH0 could also be written using nested list comprehensions:
def matrixH0(k):
return [[math.sqrt(n+m+1)/2. if abs(m-n)==1 else 0 for n in range(k)]
for m in range(k)]
You never create a multidimensional array in your code, you just append to a single list. Here is a solution:
def matrixH0(k):
H0=[]
print H0
for m in range (0,k):
H0.append([])
for n in range (0,k):
if abs(m-n)==1:
H0[m].append(math.sqrt(n+m+1)/2.)
else:
H0[m].append(0)
print H0
Init the rows at on the first loop and append the numbers to the array under the first loop index
def matrixH0(k):
H0=[]
print H0
for m in range (0,k):
H0.append([])
for n in range (0,k):
if abs(m-n)==1:
H0[m].append(math.sqrt(n+m+1)/2.)
else:
H0[m].append(0)
print H0
you find the correct Function
def matrixH0(k):
H1=[]
k=4
print H1
for m in range (0,k):
H0=[]
for n in range (0,k):
if abs(m-n)==1:
H0.append(math.sqrt(n+m+1)/2.)
else:
H0.append(0)
H1.append(H0)
return H1
[[0, 0.7071067811865476, 0, 0], [0.7071067811865476, 0, 1.0, 0], [0, 1.0, 0, 1.224744871391589], [0, 0, 1.224744871391589, 0]]
I think Raulucco's answer will work. But you if you work with number and matrix, numpy is certainly the module you want.
Your code will look like
import numpy
H0 = numpy.diag([math.sqrt(n + 1) for n in xrange(k - 1)], 1) + \
numpy.diag([math.sqrt(n) for n in xrange(k - 1)], -1)

Categories