w3resource

R Programming: Create an Array of Two 3x3 Matrices from Vectors

R Programming: Array Exercise-2 with Solution

Write a R program to create an array of two 3x3 matrices each with 3 rows and 3 columns from two given two vectors.

Sample Solution :

R Programming Code :

# Print a message indicating that two vectors of different lengths will be displayed
print("Two vectors of different lengths:")

# Create a vector v1 with elements 1, 3, 4, and 5
v1 =  c(1,3,4,5)

# Create a vector v2 with elements 10, 11, 12, 13, 14, and 15
v2 =  c(10,11,12,13,14,15)

# Print the contents of the vector v1
print(v1)

# Print the contents of the vector v2
print(v2)

# Combine vectors v1 and v2 and create a 3-dimensional array result with dimensions 3x3x2
result = array(c(v1,v2),dim = c(3,3,2))

# Print a message indicating that the new array will be displayed
print("New array:")

# Print the contents of the 3-dimensional array result
print(result)

Output:

[1] "Two vectors of different lengths:"
[1] 1 3 4 5
[1] 10 11 12 13 14 15
[1] "New array:"
, , 1

     [,1] [,2] [,3]
[1,]    1    5   12
[2,]    3   10   13
[3,]    4   11   14

, , 2

     [,1] [,2] [,3]
[1,]   15    4   11
[2,]    1    5   12
[3,]    3   10   13                         

Explanation:

  • print("Two vectors of different lengths:")
    • Prints a message indicating that two vectors of different lengths are about to be displayed.
  • v1 = c(1,3,4,5)
    • Creates a vector v1 with the elements 1, 3, 4, and 5.
  • v2 = c(10,11,12,13,14,15)
    • Creates a vector v2 with the elements 10, 11, 12, 13, 14, and 15.
  • print(v1)
    • Prints the contents of the vector v1.
  • print(v2)
    • Prints the contents of the vector v2.
  • result = array(c(v1,v2),dim = c(3,3,2))
    • Combines vectors v1 and v2 into a single vector and creates a 3-dimensional array result with dimensions 3x3x2. The combined vector is used to fill the array, which will contain two 3x3 matrices.
  • print("New array:")
    • Prints a message indicating that the new array will be displayed next.
  • print(result)
    • Prints the contents of the 3-dimensional array result, showing the two 3x3 matrices formed from the combined vectors.

R Programming Code Editor:



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

Previous: Write a R program to convert a given matrix to a 1 dimensional array.
Next: Write a R program to create an 3 dimensional array of 24 elements using the dim() function.

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/array/r-programming-array-exercise-2.php