w3resource

Concatenate two Given Matrices of the same Column but different rows in R Programming

R Programming: Matrix Exercise-13 with Solution

Write a R program to concatenate two given matrixes of same column but different rows.

Sample Solution:

R Programming Code:

# Create the first matrix with values 1 to 12 and 3 columns
x = matrix(1:12, ncol=3)

# Create the second matrix with values 13 to 24 and 3 columns
y = matrix(13:24, ncol=3)

# Print the first matrix
print("Matrix-1")
print(x)

# Print the second matrix
print("Matrix-2")
print(y)

# Concatenate the two matrices by rows and get the dimensions of the result
result = dim(rbind(x, y))

# Print the dimensions of the concatenated matrix
print("After concatenating two given matrices:")
print(result)

Output:

[1] "Matrix-1"
     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12
[1] "Matrix-2"
     [,1] [,2] [,3]
[1,]   13   17   21
[2,]   14   18   22
[3,]   15   19   23
[4,]   16   20   24
[1] "After concatenating two given matrices:"
[1] 8 3              

Explanation:

  • Create First Matrix (x)
    • x = matrix(1:12, ncol=3)
    • Creates a matrix x with values from 1 to 12, arranged into 3 columns.
  • Create Second Matrix (y)
    • y = matrix(13:24, ncol=3)
    • Creates a matrix y with values from 13 to 24, arranged into 3 columns.
  • Print First Matrix
    • print("Matrix-1")
    • Displays the label "Matrix-1" for clarity.
    • print(x)
    • Prints the contents of matrix x.
  • Print Second Matrix
    • print("Matrix-2")
    • Displays the label "Matrix-2" for clarity.
    • print(y)
    • Prints the contents of matrix y.
  • Concatenate Matrices and Get Dimensions
    • result = dim(rbind(x, y))
    • Concatenates matrices x and y by rows (rbind) and stores the dimensions of the resulting matrix in result.
  • Print Dimensions of Concatenated Matrix
    • print("After concatenating two given matrices:")
    • Displays the label for the result of concatenation.
    • print(result)
    • Prints the dimensions of the concatenated matrix, showing the number of rows and columns.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to rotate a given matrix 90 degree clockwise rotation.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/matrix/r-programming-matrix-exercise-13.php