B.Sc Computer Science
R Programming - Lab
Bharathiar University
Program 2
Manipulation of vectors and matrix
Program 2 {a}- Write a R program to perform manipulation in vectors
SOURCE CODE:
# Manipulation of Vectors
# Create two numeric vectors
v1 <- c(1, 2, 3, 4, 5)
v2 <- c(1, 1, 1, 1, 1)
# Print the original vector
print("Original Numeric Vectors:")
print(v1)
print(v2)
print("Manipulation of Vectors")
print("Adding 1 to each element of the 1st vector")
m <- v1 + 1
print(m)
print("Adding 1st and 2 nd vectors")
print(v1+v2)
print("Subtract 2nd vector from 1st vector")
print(v1-v2)
print(" Multiplying two vectors")
print(v1*v2)
OUPUT
> # Manipulation of Vectors
> # Create two numeric vectors
> v1 <- c(1, 2, 3, 4, 5)
> v2 <- c(1, 1, 1, 1, 1)
>
> # Print the original vector
> print("Original Numeric Vectors:")
[1] "Original Numeric Vectors:"
> print(v1)
[1] 1 2 3 4 5
> print(v2)
[1] 1 1 1 1 1
>
> print("Manipulation of Vectors")
[1] "Manipulation of Vectors"
> print("Adding 1 to each element of the 1st vector")
[1] "Adding 1 to each element of the 1st vector"
> m <- v1 + 1
> print(m)
[1] 2 3 4 5 6
>
> print("Adding 1st and 2 nd vectors")
[1] "Adding 1st and 2 nd vectors"
> print(v1+v2)
[1] 2 3 4 5 6
>
> print("Subtract 2nd vector from 1st vector")
[1] "Subtract 2nd vector from 1st vector"
> print(v1-v2)
[1] 0 1 2 3 4
>
> print(" Multiplying two vectors")
[1] " Multiplying two vectors"
> print(v1*v2)
[1] 1 2 3 4 5
| |
|
Program 2 {b}- Write a R program to perform manipulations in matrix
SOURCE CODE:
# Manipulation of Matrix
# Create two matrices
m1 <- matrix(1:9, nrow = 3, ncol = 3)
m2 <- matrix(1:9, nrow = 3, ncol = 3)
# Print the original matrix
print("Original Matrices:")
print("Matrix 1:")
print(m1)
print("Matrix 2:")
print(m2)
print("Addition of two matrices")
print(m1+m2)
print("Subtraction of two matrices")
print(m1-m2)
print("Multiplication of two matrices")
print(m1*m2)
print("Division of two matrices")
print(m1/m2)
OUTPUT:
> # Manipulation of Matrix
>
> # Create two matrices
> m1 <- matrix(1:9, nrow = 3, ncol = 3)
> m2 <- matrix(1:9, nrow = 3, ncol = 3)
>
> # Print the original matrix
> print("Original Matrices:")
[1] "Original Matrices:"
> print("Matrix 1:")
[1] "Matrix 1:"
> print(m1)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> print("Matrix 2:")
[1] "Matrix 2:"
> print(m2)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
>
>
> print("Addition of two matrices")
[1] "Addition of two matrices"
> print(m1+m2)
[,1] [,2] [,3]
[1,] 2 8 14
[2,] 4 10 16
[3,] 6 12 18
>
> print("Subtraction of two matrices")
[1] "Subtraction of two matrices"
> print(m1-m2)
[,1] [,2] [,3]
[1,] 0 0 0
[2,] 0 0 0
[3,] 0 0 0
>
> print("Multiplication of two matrices")
[1] "Multiplication of two matrices"
> print(m1*m2)
[,1] [,2] [,3]
[1,] 1 16 49
[2,] 4 25 64
[3,] 9 36 81
>
> print("Division of two matrices")
[1] "Division of two matrices"
> print(m1/m2)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1
| |
|
No comments:
Post a Comment