Home > Mobile >  Create matrix with np (python)
Create matrix with np (python)

Time:01-31

MATLAB refugee here with a simple numpy question:

I want to copy the dimensions of a matrix, and in this new matrix add the variable i in one column and the rest with zeroes.

Pretty straightforward, but really appreciate the help!

Happy monday

CodePudding user response:

Numpy lets you initialize a zero-filled array, similiar to matlab. You can copy the dimensions of another array via its shape attribute:

import numpy as np

dimensions = (2,3)  # rows, columns
matrix_a = np.random.randn(*dimensions)  # initial matrix filled with random numbers

matrix_b = np.zeros(matrix_a.shape)  # create zero-matrix with dimensions copied from matrix a
i_col = 1  # target column. mind zero indexing, i.e. 1 = 2nd column
filler = 42
matrix_b[:, i_col] = filler  # fill target column with filler

CodePudding user response:

You create a matrix filled with zeros using np.zeros with the corresponding dimensions, then you choose the targeted column to fill it with ones

Code:

import numpy as np
n,m=int(input()),int(input())
dim = (n,m)
arr=np.zeros(dim)
col = 1  
arr[:, col] = 1
print(arr)

Input:

2
3

Output:

[[0. 1. 0.]
[0. 1. 0.]]
  •  Tags:  
  • Related