How to create a matrix in python - python

Lets say I have a matrix: [1, 2, 3] & [4, 5, 6] & [7, 8, 9]. Written down they look like:
this.
Now, I would like to create this matrix in Python, but I am not sure how to do so.
I think its written like either this:
import numpy as np
np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Or like this:
import numpy as np
np.array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
Which way should I use?

Well, the right answer to this is that, there is none :)
Actually it all depends how do you want that this matrix acts on something.
Multiplying elementwise with another matrix, matrix product or matrix vector product.

Related

numpy: floor values of array to different array of values (similar to np.floor)

It is kind of hard to explain exactly what I mean, therefore I give an example of the function I would like:
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
b = [0, 4, 5]
c = np.func(a, b)
print(c)
-->[[0, 0, 0],
[4, 5, 5],
[5, 5, 5]]
In words: every element of an array (a) should be lowered to the closest lower value of another array (b). The values could be floats.
I could do this in a loop, but I'm sure there is a numpy way of doing this.
Any tips much appreciated.

Comparing three numpy arrays so wherever one is not a given value, the other are not that given value either

Is there an effective way in which to compare all three numpy arrays at once?
For example, if the given value to check is 5, wherever the value is not 5, it should be not 5 for all three arrays.
The only way I've thought of how to do this would be checking that occurrences that arr1 != 5 & arr2 == 5 is 0. However this only checks one direction between the two arrays, and then I need to also incorporate arr3. This seems inefficient and might end up with some logical hole.
This should pass:
arr1 = numpy.array([[1, 7, 3],
[4, 5, 6],
[4, 5, 2]])
arr2 = numpy.array([[1, 2, 3],
[4, 5, 6],
[8, 5, 6]])
arr3 = numpy.array([[1, 1, 3],
[4, 5, 6],
[9, 5, 6]])
However this should fail due to arr2 having a 3 where other arrays have 5s
arr1 = numpy.array([[1, 2, 3],
[8, 5, 6],
[4, 5, 6]])
arr2 = numpy.array([[1, 2, 3],
[2, 3, 1],
[2, 5, 6]])
arr3 = numpy.array([[1, 2, 3],
[4, 5, 6],
[4, 5, 3]])
There is a general solution (regardless number of arrays). And it's quite educational:
import numpy as np #a recommended way of import
arr = np.array([arr1, arr2, arr3])
is_valid = np.all(arr==5, axis=0) == np.any(arr==5, axis=0) #introduce axis
out = np.all(is_valid)
#True for the first case, False for the second one
Is this a valid solution?
numpy.logical_and(((arr1==5)==(arr2==5)).all(), ((arr2==5)==(arr3==5)).all())
You could AND all comparisons to 5 and compare to any one of the comparisons:
A = (arr1==5)
(A==(A&(arr2==5)&(arr3==5))).all()
Output: True for the first example, False for the second
NB. This works for any number of arrays

Operations with matrices inside a loop in Python

I have two matrices, A and B.
A=np.matrix([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
B=np.matrix([[1,1,1],[2,2,2],[3,3,3],[4,4,4]])
I want to substract some of B'rows (namely 0,2 and 3) from A. I tried to use
Index=np.array([0,2,3])
for i in Index:
A[i,:]=A[i,:]-B[i,:]
but it didn't work because matriz A should look like
matrix([[0, 1, 2],
[1, 2, 3],
[4, 5, 6],
[6, 7, 8]])
and I got
matrix([[ 1, 2, 3],
[ 2, 3, 4],
[ 7, 8, 9],
[10, 11, 12]])
What's the correct way to do this operation? I took me a long time to realize this problem (the real problem I'm trying to solve has more variables) and can't seem to figure it out.
If you do mean substract, then your should use
A[i,:]=A[i,:]-B[i,:]
instead of
A[i,:]=A[i,:]+B[i,:]
Numpy has element-wise subtraction, so something like:
import numpy as np
A=np.matrix([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
B=np.matrix([[1,1,1],[2,2,2],[3,3,3],[4,4,4]])
indices = [0,2,3]
for i in indices:
A[i,:]=np.subtract(A[i,:], B[i,:])
Will give you this matrix for A:
[[0, 1, 2],
[4, 5, 6],
[4, 5, 6],
[6, 7, 8]])
Is this what you are after? For better performance you could also just change the particular rows of A:
A[indices]=np.subtract(A[indices],B[indices])
Which will give the same answer.

rotating any Multi-dimensional List without zip function [duplicate]

This question already has answers here:
How do you rotate a two dimensional array?
(64 answers)
Closed 7 years ago.
How can rotate multi-dimensional List without using the zip function, I have this list (but it can be longer):
testlist = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10,11,12]]
I want to rotate it 90 degrees clockwise and also 90 degrees counterclockwise.
ps: The reason i don't want to use zip is because this is a homework and i must write it in vanilla python .
Of course, the proper way to rotate the multi-dimensional list would be to use zip on the reversed list. I assume you've already found this in other questions here:
>>> testlist = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10,11,12]]
>>> list(zip(*testlist[::-1]))
[[10, 7, 4, 1], [11, 8, 5, 2], [12, 9, 6, 3]]
If you do not want to do that (and also don't want other builtin functions), you'll basically have to replicate the behaviour of zip. In a very simple form (e.g. just assuming that all the lists have the same length) you can do this in a nested list comprehension. Remember to rotate the list, too:
>>> [[x[i] for x in testlist[::-1]] for i in range(len(testlist[0]))]
[[10, 7, 4, 1], [11, 8, 5, 2], [12, 9, 6, 3]]
Obviously, using zip is much clearer and less error-prone. Of course, you could also spread this out to a few lines using two nested loops. Doing the same for 90 degrees counter-clockwise is left as an excercise to the reader.
I am assuming you mean transpose.
How about this?
import numpy as np
a=np.array(testlist)
print a.T #this is a view
You code would be like:
>>> import numpy as np
>>> s = np.array([[1,2,3], [4,5,6], [7,8,9]], int)
>>> s
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.rot90(s)
array([[3, 6, 9],
[2, 5, 8],
[1, 4, 7]])
>>> np.rot90(s, 3) # Rotate counterclockwise 3 times
array([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
Since you've stated it's for homework, I'll give you the steps, but not the code.
Rotate 90
Each row becomes a column (you can use 2 for loops and enumerate)
Reverse order of the rows (you can use slices with a negative step)
Rotate -90
Each row from Rotate 90 becomes a column (2 for loops and enumerate)
Reverse order of the rows (slice with a negative step)

How to split an array according to a condition in numpy?

For example, I have a ndarray that is:
a = np.array([1, 3, 5, 7, 2, 4, 6, 8])
Now I want to split a into two parts, one is all numbers <5 and the other is all >=5:
[array([1,3,2,4]), array([5,7,6,8])]
Certainly I can traverse a and create two new array. But I want to know does numpy provide some better ways?
Similarly, for multidimensional array, e.g.
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[2, 4, 7]])
I want to split it according to the first column <3 and >=3, which result is:
[array([[1, 2, 3],
[2, 4, 7]]),
array([[4, 5, 6],
[7, 8, 9]])]
Are there any better ways instead of traverse it? Thanks.
import numpy as np
def split(arr, cond):
return [arr[cond], arr[~cond]]
a = np.array([1,3,5,7,2,4,6,8])
print split(a, a<5)
a = np.array([[1,2,3],[4,5,6],[7,8,9],[2,4,7]])
print split(a, a[:,0]<3)
This produces the following output:
[array([1, 3, 2, 4]), array([5, 7, 6, 8])]
[array([[1, 2, 3],
[2, 4, 7]]), array([[4, 5, 6],
[7, 8, 9]])]
It might be a quick solution
a = np.array([1,3,5,7])
b = a >= 3 # variable with condition
a[b] # to slice the array
len(a[b]) # count the elements in sliced array
1d array
a = numpy.array([2,3,4,...])
a_new = a[(a < 4)] # to get elements less than 5
2d array based on column(consider value of column i should be less than 5,
a = numpy.array([[1,2],[5,6],...]
a = a[(a[:,i] < 5)]
if your condition is multicolumn based, then you can make a new array applying the conditions on the columns. Then you can just compare the new array with value 5(according to my assumption) to get indexes and follow above codes.
Note that, whatever i have written in (), returns the index array.

Categories

Resources