In R, you can generate random matrices using functions like matrix()
along with random number generation functions such as runif()
(for uniform distribution), rnorm()
(for normal distribution), or sample()
(for sampling from a specified set of values).
In this example,
matrix()
function to create a 3x3 matrix.runif()
function and fill the matrix with these random numbers.random_mat
.random_mat
to the console to verify the creation of the random matrix.random_mat <- matrix(runif(9), nrow = 3)
print(random_mat)
[,1] [,2] [,3] [1,] 0.1610819 0.9683421 0.9835757 [2,] 0.4251968 0.4884130 0.2276850 [3,] 0.8133103 0.8648256 0.2863711
In this example,
matrix()
function to create a 2x4 matrix.rnorm()
function and fill the matrix with these random numbers.random_mat
.random_mat
to the console to verify the creation of the random matrix.random_mat <- matrix(rnorm(8), nrow = 2)
print(random_mat)
[,1] [,2] [,3] [,4] [1,] -0.2992151 -0.1934010 0.31835647 0.2373481 [2,] 0.6937836 -1.5788677 -0.06468858 0.3125106
In this example,
values
containing a set of values from which we want to sample.matrix()
function to create a 4x3 matrix.values
vector using the sample()
function and fill the matrix with these sampled values.random_mat
.random_mat
to the console to verify the creation of the random matrix.values <- c(10, 20, 30, 40, 50)
random_mat <- matrix(sample(values, 12, replace = TRUE), nrow = 4)
print(random_mat)
[,1] [,2] [,3] [1,] 40 10 30 [2,] 50 40 20 [3,] 30 10 40 [4,] 50 30 40
In this tutorial, we learned How to Generate Random Matrices in R language with well detailed examples.