Как создать рандомную матрицу в питоне
Перейти к содержимому

# Как создать рандомную матрицу в питоне

## Simple way to create matrix of random numbers

which is extremely unreadable and does not fit on one line.

You can drop the range(len()) :

But really, you should probably use numpy.

Docstring: rand(d0, d1, . dn)

Random values in a given shape.

Create an array of the given shape and propagate it with random samples from a uniform distribution over [0, 1) .

use np.random.randint() as np.random.random_integers() is deprecated

Looks like you are doing a Python implementation of the Coursera Machine Learning Neural Network exercise. Here’s what I did for randInitializeWeights(L_in, L_out)

For creating an array of random numbers NumPy provides array creation using:

Real numbers

Integers

For creating array using random Real numbers: there are 2 options

1. random.rand (for uniform distribution of the generated random numbers )
2. random.randn (for normal distribution of the generated random numbers )

For creating array using random Integers:

• low = Lowest (signed) integer to be drawn from the distribution
• high(optional)= If provided, one above the largest (signed) integer to be drawn from the distribution
• size(optional) = Output shape i.e. if the given shape is, e.g., (m, n, k), then m * n * k samples are drawn
• dtype(optional) = Desired dtype of the result.

The given example will produce an array of random integers between 0 and 4, its size will be 5*5 and have 25 integers

## in order to create 5 by 5 matrix, it should be modified to

arr2 = np.random.randint(0,5,size = (5,5)), change the multiplication symbol* to a comma ,#

[[2 1 1 0 1][3 2 1 4 3][2 3 0 3 3][1 3 1 0 0][4 1 2 0 1]]

The given example will produce an array of random integers between 0 and 1, its size will be 1*10 and will have 10 integers

First, create numpy array then convert it into matrix . See the code below:

For random numbers out of 10. For out of 20 we have to multiply by 20.

When you say «a matrix of random numbers», you can use numpy as Pavel https://stackoverflow.com/a/15451997/6169225 mentioned above, in this case I’m assuming to you it is irrelevant what distribution these (pseudo) random numbers adhere to.

However, if you require a particular distribution (I imagine you are interested in the uniform distribution), numpy.random has very useful methods for you. For example, let’s say you want a 3×2 matrix with a pseudo random uniform distribution bounded by [low,high]. You can do this like so:

Note, you can replace uniform by any number of distributions supported by this library.

## Генераторы списков для матричных операций. Примеры

Генераторы списков удобно использовать для матриц (многомерных массивов) чисел заданной размерности. Матрицы можно представлять в виде кортежей или списков.
Лучше матрицы представлять в виде вложенных списков. В наиболее общем случае, представление двумерной матрицы в виде списка на языке Python имеет следующий вид

• MatrixName – имя матрицы;
• a11 , …, amn — элементы матрицы. Это могут быть числа, числа с плавающей запятой, символы, строки, логические значения ( true , false ). Также это могут быть более сложные объекты, например, те же списки, кортежи или множества.

Именно генераторы списков являются наиболее удобными для обработки матриц любой размерности, поскольку они позволяют автоматически сканировать строки и столбцы матриц.

###### 2.1.1. Построение матрицы заданной размерности. Элементы матрицы формируются случайным образом

Условие задачи. Построить матрицу заданной размерности m*n и вывести ее на экран. Элементы матрицы формируются случайно и имеют значение от 1 до 10 включительно.

Решение.

###### 2.1.2. Формирование двумерной матрицы заданной размерности. Элементы матрицы вводятся с клавиатуры

Условие задачи. Сформировать матрицу размерностью m×n . Значение размеров m , n и значения элементов вводятся с клавиатуры.

Решение.

###### 2.2.1. Вычисление количества элементов матрицы, которые больше 5

Условие задачи. Построить матрицу целых чисел размерностью m×n, где m — количество строк матрицы, n — количество столбцов матрицы. Значения m и n вводятся с клавиатуры. Числа в матрице формируются случайным образом и находятся в пределах от 1 до 10. Используя генератор списков вычислить количество элементов матрицы, которые более 5.

Решение.

###### 2.2.2. Задача. Исчисление суммы элементов матрицы согласно условию

Условие задачи. Задан двумерный массив целых чисел размером m×n. Определить сумму элементов массива, которые находятся в пределах [5; 10]. Элементы массива вводятся с клавиатуры.

Решение.

При формировании генератора списка для расчета суммы используется функция sum() .

###### 2.3.2. Создать результирующую матрицу на основе исходной согласно с заданным условием

Условие задачи. Задана квадратная матрица A целых чисел размерностью n . На основе матрицы A образовать матрицу B , каждый элемент которой определяется по правилу:

## How to create matrix of random numbers in Python – NumPy

This Python tutorial will focus on how to create a random matrix in Python. Here we will use NumPy library to create matrix of random numbers, thus each time we run our program we will get a random matrix.

We will create these following random matrix using the NumPy library.

• Matrix with floating values
• Random Matrix with Integer values
• Random Matrix with a specific range of numbers
• Matrix with desired size ( User can choose the number of rows and columns of the matrix )

### Create Matrix of Random Numbers in Python

We will create each and every kind of random matrix using NumPy library one by one with example. Let’s get started.

To perform this task you must have to import NumPy library. The below line will be used to import the library.

Note that np is not mandatory, you can use something else too. But it’s a better practice to use np.

Here are some other NumPy tutorials which you may like to read.

Random 1d array matrix using Python NumPy library

The elements of the array will be greater than zero and less than one.

2d matrix using np.random.rand()

Create a 3D matrix of random numbers in Python

#### np.random.rand() to create random matrix

All the numbers we got from this np.random.rand() are random numbers from 0 to 1 uniformly distributed. You can also say the uniform probability between 0 and 1.

• Parameters: It has parameter, only positive integers are allowed to define the dimension of the array. If you want to create a 1d array then use only one integer in the parameter. To make a 2d array matrix put 2 integers. The first integer is the number of rows and the 2nd one is the number of columns.
• Return Type: ndarray

#### Create matrix of random integers in Python

In order to create a random matrix with integer elements in it we will use:

• np.random.randint(lower_range,higher_range,size=(m,n),dtype=’type_here’)

Here the default dtype is int so we don’t need to write it.

lowe_range and higher_range is int number we will give to set the range of random integers.

m,n is the size or shape of array matrix. m is the number of rows and n is the number of columns.

higher_range is optional.

Here are a few examples of this with output:

##### Examples of np.random.randint() in Python

Matrix of random integers in a given range with specified size

Here the matrix is of 3*4 as we defined 3 and 4 in size=()

All the random elements are from 1 to 10 as we defined the lower range as 1 and higher as 10.

Matrix of 0 and 1 randomly

Note that: If you define the parameters as we defined in the above program, the first parameter will be considered as a higher range automatically. And the lower range will be set to zero by default.

## How to create a matrix of random numbers with numpy in python ?

There are multiple solutions to create a matrix of random numbers in python. Let’s see some examples here:

#### Create a matrix of random integers

To create a matrix of random integers, a solution is to use numpy.random.randint

Another example with a matrix of size=(4,3)

#### Create always the same random numbers

Note: to make your work reproductible it is sometimes important to generate the same random numbers. To do that a solution is to use numpy.random.seed:

you can choose any seed number (It is common to use 42. To understand why go see: the «The Hitchhiker’s Guide to the Galaxy (travel guide)’s book»)

will always gives the same random numbers:

#### Create a matrix of random floats between 0 and 1

To create a matrix of random floats between 0 and 1, a solution is to use numpy.random.rand

Note: to generate for example random floats between 0 and 100 just multiply the matrix by 100:

gives for example

#### Create a matrix of random floats between -1 and 1

To create a matrix of negative and positive random floats, a solution is to use numpy.random.uniform

Note: can be also used to generate random numbers for other range, for example [-10,5]:

#### Create a matrix of random numbers from a standard normal distribution

To generate a random numbers from a standard normal distribution ($\mu_0=0$ , $\sigma=1$)

How to generate random numbers from a normal (Gaussian) distribution in python ?

#### Create a matrix of random numbers from a normal distribution

If we know how to generate random numbers from a standard normal distribution, it is possible to generate random numbers from any normal distribution with the formula $$X = Z * \sigma + \mu$$ where Z is random numbers from a standard normal distribution, $\sigma$ the standard deviation $\mu$ the mean.

How to generate random numbers from a normal (Gaussian) distribution in python ?

Author

#### Benjamin

Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.