![]() |
VOOZH | about |
Matrices in R Programming Language are the objects in which the elements are arranged in a 2-D rectangular layout. A matrix is a collection of elements of the same data type(numeric, character, or logical) arranged in a fixed number of rows and columns, as we very well know rows are represented horizontally and columns are represented vertically.
To create a matrix in R, we use the matrix() function. This function takes several arguments, including data(collection of elements), nrow, ncol, byrow.
Syntax: matrix(data, nrow, ncol, byrow=True)
Output:
My 3*3 matrix :-
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 40 50 60
[3,] 70 80 90
Suppose we have a 3*3 matrix i.e. 9 elements and now we need to access each element separately. Let's examine an example code to understand this.
Output:
My 3*3 matrix is:
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 40 50 60
[3,] 70 80 90
Element at position ( 1 , 1 ) is: 10
Element at position ( 1 , 2 ) is: 20
Element at position ( 1 , 3 ) is: 30
Element at position ( 2 , 1 ) is: 40
Element at position ( 2 , 2 ) is: 50
Element at position ( 2 , 3 ) is: 60
Element at position ( 3 , 1 ) is: 70
Element at position ( 3 , 2 ) is: 80
Element at position ( 3 , 3 ) is: 90
Now, we are now well-equipped to calculate the sum of all elements in a matrix. We have above covered the process of matrix creation and explored various methods of accessing its elements.
Output:
MY 3*3 matrix is:
[,1] [,2] [,3]
[1,] 10 20 30
[2,] 40 50 60
[3,] 70 80 90
Sum of all elements in the matrix are: 450
Output:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Sum of elements in row 1 : 6
Sum of elements in row 2 : 15
Sum of elements in row 3 : 24
Total sum of all elements: 45
Output:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
Sum of elements in column 1 : 12
Sum of elements in column 2 : 15
Sum of elements in column 3 : 18
Total sum of all elements: 45