Matrix size in Python - python

a is a 2x2 matrix
b is a 2x1 matrix
c is a 1x2 matrix
But ... what kind of matrices d is?
import numpy as np
a= np.array([[1,2],[3,4]])
b= np.array([[1],[2]])
c= np.array([[1,2]])
d= np.array([1,2])
Variable explorer

The variable d is not a matrix but a row vector.
import numpy as np
a= np.array([[1,2],[3,4]])
b= np.array([[1],[2]])
c= np.array([[1,2]])
d= np.array([1,2])
print(a.shape, b.shape, c.shape, d.shape)
print(a.ndim, b.ndim, c.ndim, d.ndim)
outputs shapes:
(2, 2) (2, 1) (1, 2) (2,)
and dimensions:
2 2 2 1
The number of brackets indicate the number of dimensions, for example:
e = np.array([[[1,2]]])
outputs shape (1, 1, 2) and ndim 3 (so 3 dimensional).

It's a 1-dimensional array with 2 elements in it.
Check the output in the sandbox.

Related

Numpy Matrix Subtraction Different Dimensions

I currently have a 5D numpy array of dimensions 40 x 3 x 3 x 5 x 1000 where the dimensions are labelled by a x b x c x d x e respectively.
I have another 2D numpy array of dimensions 3 x 1000 where the dimensions are labelled by b x e respectively.
I wish to subtract the 5D array from the 2D array.
One way I was thinking of was to expand the 2D into a 5D array (since the 2D array does not change for all combinations of the other 3 dimensions). I am not sure what array method/numpy function I can use to do this.
I tend to start getting lost with nD array manipulations. Thank you for assisting.
In [217]: a,b,c,d,e = 2,3,4,5,6
In [218]: A = np.ones((a,b,c,d,e),int); B = np.ones((b,e),int)
In [219]: A.shape
Out[219]: (2, 3, 4, 5, 6)
In [220]: B.shape
Out[220]: (3, 6)
In [221]: B[None,:,None,None,:].shape # could also use reshape()
Out[221]: (1, 3, 1, 1, 6)
In [222]: C = B[None,:,None,None,:]-A
In [223]: C.shape
Out[223]: (2, 3, 4, 5, 6)
The first None isn't essential; numpy will add it as needed, but as a human it might help to see it.
IIUC, suppose your arrays are a and b:
np.swapaxes(np.swapaxes(a, 1, 3) - b, 1, 3)

Numpy Matrix Multiplication with Vectors

i wanna do a simple matrix multiplication with 2 Vectors: so that A * B.T = 3x3Matrix.
But somehow numpy returns a scalar or vector.
i already tried:
np.dot(a, b.transpose())
np.matmul(a, b.transpose())
a * b.transpose()
But nothins works, it seems like a simple operation to me, but i just cannot solve it
The reason why you are getting a scalar because you are multiplying two 1D vectors in numpy, which produces the inner product of 2 vectors. You need to reshape your vector to the shape (3,1), which turns them into a 2D shape and then you get the expected result upon performing the vector multiplication. Check the snippet below
>>> import numpy as np
>>> A = np.array([1,2,3])
>>> B = np.array([4,5,6])
>>> A.shape
(3,)
>>> B.shape
(3,)
>>> AA = A.reshape(3, 1)
>>> BB = B.reshape(3, 1)
>>> AA.shape
(3, 1)
>>> BB.shape
(3, 1)
>>> np.matmul(AA, np.transpose(BB))
array([[ 4, 5, 6],
[ 8, 10, 12],
[12, 15, 18]])
Using numpy.reshape works for me all the time.
Maybe you're stumbling on it because of your matrix's size.
A should be (3,1) dan B.transpose should be (1,3).
When using numpy.dot, both matrix should have the same inner size. In your case is (1). The inner should be 1 because the inner of AxA_transpose is (3,1)x(1,3). Result will be 3x3 matrix.
Do:
A_ = np.reshape(A,(1,-1)) # array (3,1)
B_ = np.reshape(B,(1,-1))
C = np.dot(A_,B_.T) # T for transpose

3-D numpy matrix multiplication in numpy to get 1 D array

I've 2 3-D matrix of this form:
a = np.random.randint(0, 100, size=(3, 4, 3))
b = np.random.normal(0, 1, size=(3,3, 4))
I want to multiply these 2 matrices, in such a way that I get a matrix of this form:
a_b = np.random.normal(0,1,size = (3,1))
I can change the matrix shape of b in anyway to get a_b shape. E.g. I can make b 2X2 matrix or change the shape of the matrix in any other way.
Can someone please guide me?
Thanks!

importing a python sparse matrix into MATLAB

I've a Sparse matrix in CSR Sparse format in python and I want to import it to MATLAB. MATLAB does not have a CSR Sparse format. It has only 1 Sparse format for all kind of matrices. Since the matrix is very large in the dense format I was wondering how could I import it as a MATLAB sparse matrix?
The scipy.io.savemat saves sparse matrices in a MATLAB compatible format:
In [1]: from scipy.io import savemat, loadmat
In [2]: from scipy import sparse
In [3]: M = sparse.csr_matrix(np.arange(12).reshape(3,4))
In [4]: savemat('temp', {'M':M})
In [8]: x=loadmat('temp.mat')
In [9]: x
Out[9]:
{'M': <3x4 sparse matrix of type '<type 'numpy.int32'>'
with 11 stored elements in Compressed Sparse Column format>,
'__globals__': [],
'__header__': 'MATLAB 5.0 MAT-file Platform: posix, Created on: Mon Sep 8 09:34:54 2014',
'__version__': '1.0'}
In [10]: x['M'].A
Out[10]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
Note that savemat converted it to csc. It also transparently takes care of the index starting point difference.
And in Octave:
octave:4> load temp.mat
octave:5> M
M =
Compressed Column Sparse (rows = 3, cols = 4, nnz = 11 [92%])
(2, 1) -> 4
(3, 1) -> 8
(1, 2) -> 1
(2, 2) -> 5
...
octave:8> full(M)
ans =
0 1 2 3
4 5 6 7
8 9 10 11
The Matlab and Scipy sparse matrix formats are compatible. You need to get the data, indices and matrix size of the matrix in Scipy and use them to create a sparse matrix in Matlab. Here's an example:
from scipy.sparse import csr_matrix
from scipy import array
# create a sparse matrix
row = array([0,0,1,2,2,2])
col = array([0,2,2,0,1,2])
data = array([1,2,3,4,5,6])
mat = csr_matrix( (data,(row,col)), shape=(3,4) )
# get the data, shape and indices
(m,n) = mat.shape
s = mat.data
i = mat.tocoo().row
j = mat.indices
# display the matrix
print mat
Which prints out:
(0, 0) 1
(0, 2) 2
(1, 2) 3
(2, 0) 4
(2, 1) 5
(2, 2) 6
Use the values m, n, s, i, and j from Python to create a matrix in Matlab:
m = 3;
n = 4;
s = [1, 2, 3, 4, 5, 6];
% Index from 1 in Matlab.
i = [0, 0, 1, 2, 2, 2] + 1;
j = [0, 2, 2, 0, 1, 2] + 1;
S = sparse(i, j, s, m, n, m*n)
Which gives the same Matrix, only indexed from 1.
(1,1) 1
(3,1) 4
(3,2) 5
(1,3) 2
(2,3) 3
(3,3) 6

How to multiply numpy 2D array with numpy 1D array?

The two arrays:
a = numpy.array([[2,3,2],[5,6,1]])
b = numpy.array([3,5])
c = a * b
What I want is:
c = [[6,9,6],
[25,30,5]]
But, I am getting this error:
ValueError: operands could not be broadcast together with shapes (2,3) (2)
How to multiply a nD array with 1D array, where len(1D-array) == len(nD array)?
You need to convert array b to a (2, 1) shape array, use None or numpy.newaxis in the index tuple:
import numpy
a = numpy.array([[2,3,2],[5,6,1]])
b = numpy.array([3,5])
c = a * b[:, None]
Here is the document.
Another strategy is to reshape the
second array, so it has the same number of dimensions as the first array:
c = a * b.reshape((b.size, 1))
print(c)
# [[ 6 9 6]
# [25 30 5]]
Alternatively, the shape attribute of the second array can be modified in-place:
b.shape = (b.size, 1)
print(a.shape) # (2, 3)
print(b.shape) # (2, 1)
print(a * b)
# [[ 6 9 6]
# [25 30 5]]

Categories

Resources