Create a Matrix in R from a Given Vector of numbers
Write a R program to create a matrix taking a given vector of numbers as input. Display the matrix.
Sample Solution:
R Programming Code:
# Create a matrix with the numbers 1 to 16, arranged in 4 rows and filled by row
M = matrix(c(1:16), nrow = 4, byrow = TRUE)
# Print a message indicating the matrix being displayed
print("Original Matrix:")
# Print the matrix
print(M)
Output:
[1] "Original Matrix:" [,1] [,2] [,3] [,4] [1,] 1 2 3 4 [2,] 5 6 7 8 [3,] 9 10 11 12 [4,] 13 14 15 16
Explanation:
- M = matrix(c(1:16), nrow = 4, byrow = TRUE):
- Creates a matrix M using the numbers 1 to 16.
- The matrix is arranged with 4 rows (nrow = 4).
- The byrow = TRUE argument specifies that the matrix should be filled by rows (i.e., from left to right across each row).
- print("Original Matrix:"):
- Prints the message "Original Matrix:" to indicate the start of the matrix output.
- print(M):
- Prints the matrix M to display its contents, showing a 4x4 matrix filled with numbers from 1 to 16 in row-major order.
Go to:
PREV : Write a R program to create a blank matrix.
NEXT : Write a R program to create a matrix taking a given vector of numbers as input and define the column and row names. Display the matrix.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?