matrix multiplication with a constant - python

I Want to multiply the given 1x1x3 matrix with a constant value.
a= [[[1, 2, 3]]]
expected result is
a*3 = [[[3,6,9]]]
please help me to solve this

Use NumPy:
In [1]: import numpy as np
In [2]: a = np.array([[[1, 2, 3]]])
In [3]: a
Out[3]: array([[[1, 2, 3]]])
In [4]: a*3
Out[4]: array([[[3, 6, 9]]])

Try:
a= [[[1, 2, 3]]]
for i in range(len(a[0][0])):
a[0][0][i] *= 3
print a

Here's one way using list comprehensions:
>>> a = [[[1, 2, 3]]]
>>> b = [[x*3 for x in a[0][0]]]
>>> b
[[3, 6, 9]]

Here is a way to do it using pure Python:
a3 = [[[el * 3 for el in col] for col in row] for row in a]
This works with 3D matrices of any shape, not just 1x1x3.
However, if this is the sort of thing you need to do on a regular basis, I would encourage you to learn NumPy. Then you'll be able to write:
a3 = a * 3

Related

Add elements to 2-D array

I have the following Arrays
import numpy as np
A = np.array([[1,2], [3,4]])
B = np.array([5,6])
Now I want to add the second element of A to B using the append function:
B = np.append(B, A[1])
What I want to get is:
B = np.array([[5, 6],[3,4]])
But what I get is:
B = np.array([5, 6, 3, 4])
How can I solve this? Should I use another function instead of numpy.append?
import numpy as np
A = np.array([[1,2], [3,4]])
B = np.array([[5,6]])
B = np.append(B, [A[1]], axis=0)
print(B)
Output
array([[5, 6],
[3, 4]])
This would be one of the way using np.append() specifying the axis = 0.
You can use np.stack for this instead of np.append:
>>> np.stack([B, A[1]])
array([[5, 6],
[3, 4]])
You could also add [:, None] to your two arrays and append with axis=1:
>>> np.append(B[:, None], A[1][:, None], axis=1)
array([[5, 3],
[6, 4]])

Numpy merge two arrays can i make a numpy array like this?

I am trying two array like this. It's different from column_stack so I am not able to find how to do it from documentation or google search.
I have arrays a and b. How can I make c from them ?
a = [[1, 2],[3, 4]]
b = [[5 , 6]]
c = [[[1, 2],[5]],
[3, 4],[6]]]
I need this to input the values to theanets.
In [54]:
a = np.array([[1, 2],[3, 4]])
a
Out[54]:
array([[1, 2],
[3, 4]])
In [55]:
b = np.array([[5 , 6]])
b
Out[55]:
array([[5, 6]])
In [96]:
c = [[a[n].tolist() , b[:,n].tolist()] for n in range(len(a))]
c
Out[96]:
[[[1, 2], [5]], [[3, 4], [6]]]

Extract specific array from multi dimensional array with index sets

Suppose inputs are like below.
indexSet1 = [0,1,2]
indexSet2 = [1,2]
A = [[1,2,3],[4,5,6],[7,8,9]]
Then I want to get a matrix whose height is 3 and width is 2 respectively and elements corresponds to indexSet1's value and indexSet2's one.
In short, I want to a array [[2,3],[4,5],[7,8]] from A by indexSet1 and indexSet2.
When I code like below, I can not get my desire result.
>>> import numpy as np
>>> np.array(A)[np.array(indexSet1),np.array(indexSet2)]
array([5, 9])
Can anyone know wise methods?
Sorry for my poor English.
And thank you in advance.
Using nested list comprehension:
>>> indexSet1 = [0,1,2]
>>> indexSet2 = [1,2]
>>> A = [[1,2,3],[4,5,6],[7,8,9]]
>>> [[A[i][j] for j in indexSet2] for i in indexSet1]
[[2, 3], [5, 6], [8, 9]]
In NumPy you can do something like this:
>>> A = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> A[np.array(indexSet1)[:, None], indexSet2]
array([[2, 3],
[5, 6],
[8, 9]])

Howto expand 2D NumPy array by copy bottom row and right column?

I have a 2D NumPy array and I hope to expand its size on both dimensions by copying the bottom row and right column.
For example, from 2x2:
[[0,1],
[2,3]]
to 4x4:
[[0,1,1,1],
[2,3,3,3],
[2,3,3,3],
[2,3,3,3]]
What's the best way to do it?
Thanks.
Here, the hstack and vstack functions can come in handy. For example,
In [16]: p = array(([0,1], [2,3]))
In [20]: vstack((p, p[-1], p[-1]))
Out[20]:
array([[0, 1],
[2, 3],
[2, 3],
[2, 3]])
And remembering that p.T is the transpose:
So now you can do something like the following:
In [16]: p = array(([0,1], [2,3]))
In [22]: p = vstack((p, p[-1], p[-1]))
In [25]: p = vstack((p.T, p.T[-1], p.T[-1])).T
In [26]: p
Out[26]:
array([[0, 1, 1, 1],
[2, 3, 3, 3],
[2, 3, 3, 3],
[2, 3, 3, 3]])
So the 2 lines of code should do it...
Make an empty array and copy whatever rows, columns you want into it.
def expand(a, new_shape):
x, y = a.shape
r = np.empty(new_shape, a.dtype)
r[:x, :y] = a
r[x:, :y] = a[-1:, :]
r[:x, y:] = a[:, -1:]
r[x:, y:] = a[-1, -1]
return r

Select a submatrix based on diagonal value

I want to select a submatrix of a numpy matrix based on whether the diagonal is less than some cutoff value. For example, given the matrix:
Test = array([[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7],
[4,5,6,7,8],
[5,6,7,8,9]])
I want to select the rows and columns where the diagonal value is less than, say, 6. In this example, the diagonal values are sorted, so that I could just take Test[:3,:3], but in the general problem I want to solve this isn't the case.
The following snippet works:
def MatrixCut(M,Ecut):
D = diag(M)
indices = D<Ecut
n = sum(indices)
NewM = zeros((n,n),'d')
ii = -1
for i,ibool in enumerate(indices):
if ibool:
ii += 1
jj = -1
for j,jbool in enumerate(indices):
if jbool:
jj += 1
NewM[ii,jj] = M[i,j]
return NewM
print MatrixCut(Test,6)
[[ 1. 2. 3.]
[ 2. 3. 4.]
[ 3. 4. 5.]]
However, this is fugly code, with all kinds of dangerous things like initializing the ii/jj indices to -1, which won't cause an error if somehow I get into the loop and take M[-1,-1].
Plus, there must be a numpythonic way of doing this. For a one-dimensional array, you could do:
D = diag(A)
A[D<Ecut]
But the analogous thing for a 2d array doesn't work:
D = diag(Test)
Test[D<6,D<6]
array([1, 3, 5])
Is there a good way to do this? Thanks in advance.
This also works when the diagonals are not sorted:
In [7]: Test = array([[1,2,3,4,5],
[2,3,4,5,6],
[3,4,5,6,7],
[4,5,6,7,8],
[5,6,7,8,9]])
In [8]: d = np.argwhere(np.diag(Test) < 6).squeeze()
In [9]: Test[d][:,d]
Out[9]:
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
Alternately, to use a single subscript call, you could do:
In [10]: d = np.argwhere(np.diag(Test) < 6)
In [11]: Test[d, d.flat]
Out[11]:
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
[UPDATE]: Explanation of the second form.
At first, it may be tempting to just try Test[d, d] but that will only extract elements from the diagonal of the array:
In [75]: Test[d, d]
Out[75]:
array([[1],
[3],
[5]])
The problem is that d has shape (3, 1) so if we use d in both subscripts, the output array will have the same shape as d. The d.flat is equivalent to using d.flatten() or d.ravel() (except flat just returns an iterator instead of an array). The effect is that the result has shape (3,):
In [76]: d
Out[76]:
array([[0],
[1],
[2]])
In [77]: d.flatten()
Out[77]: array([0, 1, 2])
In [79]: print d.shape, d.flatten().shape
(3, 1) (3,)
The reason Test[d, d.flat] works is because numpy's general broadcasting rules cause the last dimension of d (which is 1) to be broadcast to the last (and only) dimension of d.flat (which is 3). Similarly, d.flat is broadcast to match the first dimension of d. The result is two (3,3) index arrays, which are equivalent to the following arrays i and j:
In [80]: dd = d.flatten()
In [81]: i = np.hstack((d, d, d)
In [82]: j = np.vstack((dd, dd, dd))
In [83]: print i
[[0 0 0]
[1 1 1]
[2 2 2]]
In [84]: print j
[[0 1 2]
[0 1 2]
[0 1 2]]
And just to make sure they work:
In [85]: Test[i, j]
Out[85]:
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
The only way I found to solve your task is somewhat tricky
>>> Test[[[i] for i,x in enumerate(D<6) if x], D<6]
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])
possibly not the best one. Based on this answer.
Or (thanks to #bogatron or reminding me argwhere):
>>> Test[np.argwhere(D<6), D<6]
array([[1, 2, 3],
[2, 3, 4],
[3, 4, 5]])

Categories