A program that will create a square matrix of any size the values on its diagonals are 1, and the remaining values of the matrix are 0.
matrix = []
dimension = int (input ("Enter matrix unit size:"))
for i in range (0, dimension):
for j in range (0, dimension):
if i == j:
matrix.append (1)
else:
matrix.append (0)
print (matrix)
I need matrix like [[],[],[]], how?
matrix[[i]].append(1) - doesn't work
You need to insert one row to matrix before entering the for j loop, and then add the element to the row, rather than to the matrix.
matrix = []
dimension = int(input("Enter identity matrix size:"))
for i in range(0, dimension):
row = []
matrix.append(row)
for j in range(0, dimension):
if i == j:
row.append(1)
else:
row.append(0)
print(matrix)
You could let
matrix = [[1 if i == j else 0 for i in range(dimension)] for j in range(dimension)]
Note, though, that any sort of linear algebra will be much more conveniently carried out in NumPy/SciPy. In NumPy, for instance, the identity matrix would be produced with numpy.eye through
import numpy as np
np.eye(dimension)
and in SciPy, using scipy.sparse.identity,
from scipy.sparse import identity
identity(dimension)
import numpy as np
matrix = []
dimension = int (input ("Enter matrix unit size:"))
for i in range (0, dimension):
for j in range (0, dimension):
if i == j:
matrix.append (1)
else:
matrix.append (0)
npmatrix = np.array(matrix)
npmatrix = npmatrix.reshape(dimension,dimension)
print(npmatrix)
Related
Is there an efficient way to represent a sparse matrix as ijv (3 arrays : row, column, value) form.
Using nested loop seems very naive and slow for large matrices.
The code comes from here:
# Python program for Sparse Matrix Representation
# using arrays
# assume a sparse matrix of order 4*5
# let assume another matrix compactMatrix
# now store the value,row,column of arr1 in sparse matrix compactMatrix
sparseMatrix = [[0,0,3,0,4],[0,0,5,7,0],[0,0,0,0,0],[0,2,6,0,0]]
# initialize size as 0
size = 0
for i in range(4):
for j in range(5):
if (sparseMatrix[i][j] != 0):
size += 1
# number of columns in compactMatrix(size) should
# be equal to number of non-zero elements in sparseMatrix
rows, cols = (3, size)
compactMatrix = [[0 for i in range(cols)] for j in range(rows)]
k = 0
for i in range(4):
for j in range(5):
if (sparseMatrix[i][j] != 0):
compactMatrix[0][k] = i
compactMatrix[1][k] = j
compactMatrix[2][k] = sparseMatrix[i][j]
k += 1
for i in compactMatrix:
print(i)
# This code is contributed by MRINALWALIA
I am going to print sparse matrix to file in ijv form and read it in C++.
scipy.sparse.coo_matrix just give me:
print(coo_matrix([[0,0,3,0,4],[0,0,5,7,0],[0,0,0,0,0],[0,2,6,0,0]]))
(0, 2) 3
(0, 4) 4
(1, 2) 5
(1, 3) 7
(3, 1) 2
(3, 2) 6
with np.where() I can get the index of nonzero elements, but how about the v array?
Probably do you know a more efficient method (I am not going to use swig, ... to wrap the code)?
Edit
size=np.count_nonzero(sparseMatrix)
rows, cols = np.where(sparseMatrix)
compactMatrix = np.zeros((3, size))
for i in range(size):
compactMatrix[0][i] = rows[i]
compactMatrix[1][i] = cols[i]
compactMatrix[2][i] = sparseMatrix[rows[i]][cols[i]]
print(compactMatrix)
That's what I thought finally.
Suppose i have an array shaped as a:
import numpy as np
n = 10
d = 5
a = np.zeros(shape = np.repeat(n,d))
And that I want to obtain the values corresponding to indexes (0,...,:,...,0) for the : along dimensions, resulting in a (n,d)-shaped array b, with b[i,j] = a[0,...,0,i,0,...,0] where the i is in the jth dimension.
How can i extractb from a ?
Get the flattened indices and just index for a vectorized solution -
n = len(a)
d = a.ndim
idxs = np.multiply.outer(n**np.arange(d), np.arange(n))
out = a.flat[idxs]
Easiest is to do a for loop:
# get the first slice of `a` along given dimension `j`
def get_slice(a,j):
idx = [0]*len(a.shape)
idx[j] = slice(None)
return a[tuple(idx)]
out = np.stack([get_slice(a,j) for j in range(len(a.shape))])
And out.shape is (10,5)
I have a repeated experiment (n=K) which measures time series of equal length N, i.e. my data matrix has the shape NxK. I now want to compute a robust estimate of the covariance between the experiments for which I use the Minimum Covariance Determinent algorithm implemented in Sci Kit Learn.
One way to apply the algorithm is to directly apply the function to the data array D, i.e.:
import numpy as np
from sklearn.covariance import MinCovDet
N = 300 #number of rows
K = 40 #number of columns
D = np.random.normal(0, 1, size=(N, K)) #create random Data
mcd = MinCovDet().fit(D) #yields a KxK matrix
cov_mat = mcd.covariance_ #covariances between the columns
another way is to loop over the experiments
cov_loop = np.zeros((K, K))
for i in range(0, K):
for j in range(i, K):
temp_arr = np.zeros((N, 2))
temp_arr[:, 0] = D[:, i]
temp_arr[:, 1] = D[:, j]
mcd_temp = MinCovDet().fit(temp_arr)
cov_temp = mcd_temp.covariance_ #yields 2x2 matrix, we are only interested in the [0,1] element
cov_loop[i, j] = cov_temp[0, 1]
cov_loop[j, i] = cov_loop[i, j]
print(cov_loop/cov_mat)
The results differ significantly, which is why I wanted to ask what went wrong here.
I have an array with m rows and arrays as values, which indicate the index of columns and are bounded to a large number n.
E.g:
Y = [[1,34,203,2032],...,[2984]]
Now I want an efficient way to initialize a sparse numpy matrix X with dimensions m,n and values corresponding to Y (X[i,j] = 1, if j is in Y[i], = 0 otherwise).
Your data are already close to csr format, so I suggest using that:
import numpy as np
from scipy import sparse
from itertools import chain
# create an example
m, n = 20, 10
X = np.random.random((m, n)) < 0.1
Y = [list(np.where(y)[0]) for y in X]
# construct the sparse matrix
indptr = np.fromiter(chain((0,), map(len, Y)), int, len(Y) + 1).cumsum()
indices = np.fromiter(chain.from_iterable(Y), int, indptr[-1])
data = np.ones_like(indices)
S = sparse.csr_matrix((data, indices, indptr), (m, n))
# or
S = sparse.csr_matrix((data, indices, indptr))
# check
assert np.all(S==X)
I have a loop for that generate a new vector (100,) in each iteration. So the code loop likes
for i in range (10):
for j in range (4):
#Create a new vector (100,)
#Concatenate 4 vector together to make (400,) #400=4*10
#Append the concatenation vectors (400,) in vertical to make (10,400) array
My expected is that generates a matrix size of (10,400) that concatenate vectors in these loops
Currently, my solution is
matrix_= np.empty([10,400])
for i in range (10):
vector_horz=[]
for j in range (4):
#Create a new vector (100,)
vector_rnd=#Random make a vector/list with size of (100,1)
#Concatenate 4 vector together to make (400,) #400=4*10
vector_horz.append(vector_rnd)
#Append the concatenation vectors (400,) in vertical to make (10,400) array
matrix_(:,i)=vector_horz
However, it said that my size of matrix and vector_horz cannot assign. Could you give me another solution?
Option 1
(Recommended) First generate your data and create an array at the end:
data = []
for i in range(10):
for j in range(4):
temp_list = ... # random vector of 100 elements
data.extend(temp_list)
arr = np.reshape(data, (10, 400))
Option 2
Alternatively, initialise an empty array with np.empty and assign one slice at a time:
arr = np.empty((10, 400))
for i in range(10):
for j in range(4):
temp_list = ...
arr[i, j * 100 : (j + 1) * 100] = temp_list