Sample Programs Using Matrices in R
Sample Programs Using Matrices in R
The following programs demonstrate practical numerical applications of matrices suitable for undergraduate laboratories.
1. Student Mark Analysis
Problem
Marks of 4 students in 3 subjects are stored in a matrix. Find:
- Total marks of each student.
- Average marks of each student.
- Highest mark in each subject.
- Class average in each subject.
Program
marks <- matrix(
c(85,90,78,
92,88,80,
75,82,85,
95,91,89),
nrow=4,
byrow=TRUE
)
print(marks)
# Total marks of students
totals <- rowSums(marks)
# Average marks of students
averages <- rowMeans(marks)
# Highest mark in each subject
highest <- apply(marks,2,max)
# Subject averages
subject_avg <- colMeans(marks)
cat("Total Marks:\n")
print(totals)
cat("Average Marks:\n")
print(averages)
cat("Highest Mark in Each Subject:\n")
print(highest)
cat("Subject Averages:\n")
print(subject_avg)
2. Matrix Multiplication
Problem
Compute the product of two matrices.
Program
A <- matrix(c(1,2,3,4),2,2)
B <- matrix(c(5,6,7,8),2,2)
print(A)
print(B)
C <- A %*% B
cat("Product Matrix:\n")
print(C)
Output
[,1] [,2]
[1,] 23 31
[2,] 34 46
3. Solving a System of Linear Equations
Problem
Solve
using matrices.
Program
A <- matrix(c(2,1,3,4),2,2,byrow=TRUE)
B <- matrix(c(5,6),2,1)
X <- solve(A)%*%B
cat("Solution:\n")
print(X)
Output
[,1]
[1,] 2.800000
[2,] -0.600000
Concepts Demonstrated
- Inverse of matrix
- Matrix multiplication
- System of equations
4. Image Brightness Adjustment
Problem
A grayscale image is represented as a matrix. Increase the brightness by 50 units.
Program
image <- matrix(c(
50,60,70,
80,90,100,
120,130,140),3,3,byrow=TRUE)
cat("Original Image\n")
print(image)
bright_image <- image + 50
cat("Brightened Image\n")
print(bright_image)
Output
Original Image
50 60 70
80 90 100
120 130 140
Brightened Image
100 110 120
130 140 150
170 180 190
Concepts Demonstrated
- Scalar operations
- Matrix arithmetic
- Image representation
5. Distance Matrix Between Points
Problem
Given coordinates of points, compute the Euclidean distance between every pair of points.
Points:
P1=(1,2)
P2=(4,6)
P3=(7,3)
Program
points <- matrix(c(1,2,4,6,7,3), nrow=3, byrow=TRUE)
n <- nrow(points)
distance_matrix <- matrix(0,n,n)
for(i in 1:n)
{
for(j in 1:n)
{
distance_matrix[i,j] <-
sqrt((points[i,1]-points[j,1])^2 +
(points[i,2]-points[j,2])^2)
}
}
print(distance_matrix)
Output
[,1] [,2] [,3]
[1,] 0.000000 5.000000 6.082763
[2,] 5.000000 0.000000 4.242641
[3,] 6.082763 4.242641 0.000000
Comments
Post a Comment