The Wayback Machine - https://web.archive.org/web/20240914144232/https://www.geeksforgeeks.org/operations-on-matrices-in-r/
Open In App

Operations on Matrices in R

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Matrices in R are a bunch of values, either real or complex numbers, arranged in a group of fixed number of rows and columns. Matrices are used to depict the data in a structured and well-organized format. It is necessary to enclose the elements of a matrix in parentheses or brackets. A matrix with 9 elements is shown below. [Tex]\begin{bmatrix}1 & 2 & 3\\4 & 5 & 6\\7 & 8 & 9\end{bmatrix} [/Tex]This Matrix [M] has 3 rows and 3 columns. Each element of matrix [M] can be referred to by its row and column number. For example, a23 = 6 Order of a Matrix : The order of a matrix is defined in terms of its number of rows and columns. Order of a matrix = No. of rows × No. of columns Therefore Matrix [M] is a matrix of order 3 × 3.

Operations on Matrices

There are four basic operations i.e. DMAS (Division, Multiplication, Addition, Subtraction) that can be done with matrices. Both the matrices involved in the operation should have the same number of rows and columns.

Matrices Addition

The addition of two same ordered matrices [Tex]M_r_*_c [/Tex]and [Tex]N_r_*_c [/Tex]yields a matrix [Tex]R_r_*_c [/Tex]where every element is the sum of corresponding elements of the input matrices. 

Python

# R program to add two matrices # Creating 1st Matrix B = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd Matrix C = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columns num_of_rows = nrow(B) num_of_cols = ncol(B) # Creating matrix to store results sum = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matrices print(B) print(C)

Output:

[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
[,1] [,2] [,3]
[1,] 8 12 16
[2,] 10 14 18

In the above code, nrow(B) gives the number of rows in B and ncol(B) gives the number of columns. Here, sum is an empty matrix of the same size as B and C. The elements of sum are the addition of the corresponding elements of B and C through nested for loops. Using ‘+’ operator for matrix addition: Similarly, the following R script uses the in-built operator +: 

Python

# R program for matrix addition # using '+' operator # Creating 1st Matrix B = matrix(c(1, 2 + 3i, 5.4, 3, 4, 5), nrow = 2, ncol = 3) # Creating 2nd Matrix C = matrix(c(2, 0i, 0.1, 3, 4, 5), nrow = 2, ncol = 3) # Printing the resultant matrix print(B + C)

Output:

[,1] [,2] [,3]
[1,] 3+0i 5.5+0i 8+0i
[2,] 2+3i 6.0+0i 10+0i

R provides the basic inbuilt operator to add the matrices. In the above code, all the elements in the resultant matrix are returned as complex numbers, even if a single element of a matrix is a complex number. Properties of Matrix Addition:

  • Commutative: B + C = C + B
  • Associative: For n number of matrices A + (B + C) = (A + B) + C
  • Order of the matrices involved must be same.

Matrices Subtraction

The subtraction of two same ordered matrices [Tex]M_r_*_c [/Tex]and [Tex]N_r_*_c [/Tex]yields a matrix [Tex]R_r_*_c [/Tex]where every element is the difference of corresponding elements of the second input matrix from the first. 

Python

# R program to add two matrices # Creating 1st Matrix B = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd Matrix C = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columns num_of_rows = nrow(B) num_of_cols = ncol(B) # Creating matrix to store results diff = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matrices print(B) print(C) # Calculating diff of matrices for(row in 1:num_of_rows) { for(col in 1:num_of_cols) { diff[row, col] <- B[row, col] - C[row, col] } } # Printing resultant matrix print(diff)

Output:

[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
[,1] [,2] [,3]
[1,] -6 -6 -6
[2,] -6 -6 -6

Here in the above code, the elements of diff matrix are the subtraction of the corresponding elements of B and C through nested for loops. Using ‘-‘ operator for matrix subtraction: Similarly, the following R script uses the in-built operator ‘-‘: 

Python

# R program for matrix addition # using '-' operator # Creating 1st Matrix B = matrix(c(1, 2 + 3i, 5.4, 3, 4, 5), nrow = 2, ncol = 3) # Creating 2nd Matrix C = matrix(c(2, 0i, 0.1, 3, 4, 5), nrow = 2, ncol = 3) # Printing the resultant matrix print(B - C)

Output:

[,1] [,2] [,3]
[1,] -1+0i 5.3+0i 0+0i
[2,] 2+3i 0.0+0i 0+0i

Properties of Matrix Subtraction: 

  • Non-Commutative: B – C != C – B
  • Non-Associative: For n number of matrices A – (B – C) != (A – B) – C
  • Order of the matrices involved must be same.

Matrices Multiplication

The multiplication of two same ordered matrices [Tex]M_r_*_c [/Tex]and [Tex]N_r_*_c [/Tex]yields a matrix [Tex]R_r_*_c [/Tex]where every element is the product of corresponding elements of the input matrices. 

Python

# R program to multiply two matrices # Creating 1st Matrix B = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd Matrix C = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columns num_of_rows = nrow(B) num_of_cols = ncol(B) # Creating matrix to store results prod = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matrices print(B) print(C) # Calculating product of matrices for(row in 1:num_of_rows) { for(col in 1:num_of_cols) { prod[row, col] <- B[row, col] * C[row, col] } } # Printing resultant matrix print(prod)

Output:

[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
[,1] [,2] [,3]
[1,] 7 27 55
[2,] 16 40 72

The elements of sum are the multiplication of the corresponding elements of B and C through nested for loops. Using ‘*’ operator for matrix multiplication: Similarly, the following R script uses the in-built operator *: 

Python

# R program for matrix multiplication # using '*' operator # Creating 1st Matrix B = matrix(c(1, 2 + 3i, 5.4), nrow = 1, ncol = 3) # Creating 2nd Matrix C = matrix(c(2, 1i, 0.1), nrow = 1, ncol = 3) # Printing the resultant matrix print (B * C)

Output:

[,1] [,2] [,3]
[1,] 2+0i -3+2i 0.54+0i

Properties of Matrix Multiplication:

  • Commutative: B * C = C * B
  • Associative: For n number of matrices A * (B * C) = (A * B) * C
  • Order of the matrices involved must be same.

Matrices Division

The division of two same ordered matrices [Tex]M_r_*_c [/Tex]and [Tex]N_r_*_c [/Tex]yields a matrix [Tex]R_r_*_c [/Tex]where every element is the quotient of corresponding elements of the first matrix element divided by the second. 

Python

# R program to divide two matrices # Creating 1st Matrix B = matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3) # Creating 2nd Matrix C = matrix(c(7, 8, 9, 10, 11, 12), nrow = 2, ncol = 3) # Getting number of rows and columns num_of_rows = nrow(B) num_of_cols = ncol(B) # Creating matrix to store results div = matrix(, nrow = num_of_rows, ncol = num_of_cols) # Printing Original matrices print(B) print(C) # Calculating product of matrices for(row in 1:num_of_rows) { for(col in 1:num_of_cols) { div[row, col] <- B[row, col] / C[row, col] } } # Printing resultant matrix print(div)

Output:

[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[,1] [,2] [,3]
[1,] 7 9 11
[2,] 8 10 12
[,1] [,2] [,3]
[1,] 0.1428571 0.3333333 0.4545455
[2,] 0.2500000 0.4000000 0.5000000

The elements of div matrix are the division of the corresponding elements of B and C through nested for loops. Using ‘/’ operator for matrix division: Similarly, the following R script uses the in-built operator /: 

Python

# R program for matrix division # using '/' operator # Creating 1st Matrix B = matrix(c(4, 6i, -1), nrow = 1, ncol = 3) # Creating 2nd Matrix C = matrix(c(2, 2i, 0), nrow = 1, ncol = 3) # Printing the resultant matrix print (B / C)

Output:

[,1] [,2] [,3]
[1,] 2+0i 3+0i -Inf+NaNi

Properties of Matrix Division: 

  • Non-Commutative: B / C != C / B
  • Non-Associative: For n number of matrices A / (B / C) != (A / B) / C
  • Order of the matrices involved must be same.

Note: Time Complexity of all the matrix operations = O(r*c) where r*c is the order of the matrix.



Similar Reads

Arithmetic Operations on Images using OpenCV | Set-2 (Bitwise Operations on Binary Images)
Prerequisite: Arithmetic Operations on Images | Set-1Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are : ANDORXORNOT Also, Bitwise operations helps in image masking. Image creation can be enabled with the help of these operations. These operations can
4 min read
Python List Equality | Program to check if two given matrices are identical
We are given two square matrices of same order. Check if two given matrices are identical. Examples: Input : A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] Output: Matrices are identical We have existing solution for this problem please refer C Program to check if two give
3 min read
Combining Matrices in R
Combining matrices involves the concatenation of two or more smaller matrices, either row or column wise to form a larger matrix. It is basically a data manipulation operation where the involved matrices must be of compatible sizes to execute the operation. Matrices can be combined either horizontally or vertically. There are two ways of combining
3 min read
Multiply matrices of complex numbers using NumPy in Python
In this article, we will discuss how to multiply two matrices containing complex numbers using NumPy but first, let's know what is a complex number. A Complex Number is any number that can be represented in the form of x+yj where x is the real part and y is the imaginary part. Multiplication of two complex numbers can be done using the below formul
2 min read
Calculate inner, outer, and cross products of matrices and vectors using NumPy
Let's discuss how to find the inner, outer, and cross products of matrices and vectors using NumPy in Python. Inner Product of Vectors and Matrices To find the inner product of the vectors and matrices, we can use the inner() method of NumPy.Syntax: numpy.inner(arr1, arr2) Code : C/C++ Code # Python Program illustrating # numpy.inner() method impor
2 min read
Adding and Subtracting Matrices in Python
In this article, we will discuss how to add and subtract elements of the matrix in Python. Example: Suppose we have two matrices A and B. A = [[1,2],[3,4]] B = [[4,5],[6,7]] then we get A+B = [[5,7],[9,11]] A-B = [[-3,-3],[-3,-3]] Now let us try to implement this using Python 1. Adding elements of the matrix In the above code, we have used np.add()
4 min read
Working with Sparse Matrices in R Programming
Sparse matrices are sparsely populated collections of elements, where there is a very less number of non-null elements. Storage of sparsely populated data in a fully dense matrix leads to increased complexities of time and space. Therefore, the data structures are optimized to store this data much more efficiently and decrease the access time of el
9 min read
Fixing Non Positive Definite Correlation Matrices Using R
In this article we will discuss Fixing non-positive definite correlation matrices using R Programming Language, The correlation matrices are fundamental tools in various statistical analyses and structural equation modeling, and portfolio optimization. These matrices represent relationships between different variables and can be expected to have ce
4 min read
Merge two matrices by row names in R
In this article, we will examine various methods to merge two matrices by row names in the R programming language. What is a matrix?A matrix is defined as it is a two-dimensional data set which is the collection of rows and columns. A matrix can have the ability to contain or accept data of the same type such as integers, characters, floating point
4 min read
R - Matrices
R-matrix is a two-dimensional arrangement of data in rows and columns. In a matrix, rows are the ones that run horizontally and columns are the ones that run vertically. In R programming, matrices are two-dimensional, homogeneous data structures. These are some examples of matrices: Creating a Matrix in RTo create a matrix in R you need to use the
12 min read
Multiplication of two Matrices in Single line using Numpy in Python
Matrix multiplication is an operation that takes two matrices as input and produces single matrix by multiplying rows of the first matrix to the column of the second matrix.In matrix multiplication make sure that the number of columns of the first matrix should be equal to the number of rows of the second matrix. Example: Multiplication of two matr
3 min read
MongoDB Python - Insert and Replace Operations
This article focus on how to replace document or entry inside a collection. We can only replace the data already inserted in the database. Prerequisites : MongoDB Python Basics Method used: replace_one() Aim: Replace entire data of old document with a new document Insertion In MongoDB We would first insert data in MongoDB. C/C++ Code # Python code
3 min read
Python set operations (union, intersection, difference and symmetric difference)
This article demonstrates different operations on Python sets. Examples: Input : A = {0, 2, 4, 6, 8} B = {1, 2, 3, 4, 5} Output : Union : [0, 1, 2, 3, 4, 5, 6, 8] Intersection : [2, 4] Difference : [8, 0, 6] Symmetric difference : [0, 1, 3, 5, 6, 8] In Python, below quick operands can be used for different operations. | for union. & for interse
1 min read
Image segmentation using Morphological operations in Python
If we want to extract or define something from the rest of the image, eg. detecting an object from a background, we can break the image up into segments in which we can do more processing on. This is typically called Segmentation. Morphological operations are some simple operations based on the image shape. It is normally performed on binary images
3 min read
Find the number of operations required to make all array elements Equal
Given an array of N integers, the task is to find the number of operations required to make all elements in the array equal. In one operation we can distribute equal weights from the maximum element to the rest of the array elements. If it is not possible to make the array elements equal after performing the above operations then print -1. Examples
6 min read
Python | Arithmetic operations in excel file using openpyxl
Prerequisite: Reading & Writing to excel sheet using openpyxlOpenpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let's see how to perform different arithmetic operations using openpyxl. =SUM(cell1:cell2) : Adds all the numbers in a range of
3 min read
Python | Trigonometric operations in excel file using openpyxl
Prerequisite : Adjusting rows and columns of an excel sheet using openpyxl. Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, mathematical operations and plotting graphs. Let’s see how to perform different Trigonometric operations using openpyxl. Simple trigonometric functions : Code
3 min read
numpy string operations | isupper() function
numpy.core.defchararray.isupper(arr) function returns True for each element if all cased characters in the string are uppercase and there is at least one character, it returns false otherwise. Parameters: arr : array_like of str or unicode Returns : [ndarray] Output array of bools. Code #1: # Python Program explaining # numpy.char.isupper() functio
1 min read
numpy string operations | istitle() function
numpy.core.defchararray.istitle(arr) function returns True for each element in the array if the element is a titlecased string and there is at least one character, it returns false otherwise. Parameters: arr : array_like of str or unicode Returns : [ndarray] Output array of bools. Code #1: # Python Program explaining # numpy.char.istitle() function
1 min read
numpy string operations | islower() function
numpy.core.defchararray.islower(arr) function returns True for each element if all cased characters in the string are lowercase and there is at least one cased character, It returns false otherwise. Parameters: arr : array_like of str or unicode Returns : [ndarray] Output array of bools. Code #1: # Python Program explaining # numpy.char.islower() f
1 min read
numpy string operations | lower() function
numpy.core.defchararray.lower(arr) function is used to return an array with the elements converted to lowercase. Parameters: arr : [ array_like ] Input array which may be str or unicode. Returns : [ndarray] Output lowercased array of str or unicode, depending on input type. Code #1: # Python Program explaining # numpy.char.lower() function import n
1 min read
numpy string operations | title() function
numpy.core.defchararray.title(arr): function is used to Return element-wise title cased version of string or unicode.Title case words start with uppercase characters, all remaining cased characters are lowercase. Parameters: arr : [ array_like ] Input array which may be str or unicode. Returns : [ndarray] Output array of str or unicode, depending o
1 min read
numpy string operations | upper() function
numpy.core.defchararray.upper(arr): function is used to return an array with the elements converted to uppercase. Parameters: arr : [ array_like ] Input array which may be str or unicode. Returns : [ndarray] Output uppercased array of str or unicode, depending on input type. Code #1: # Python Program explaining # numpy.char.upper() function import
1 min read
numpy string operations | isnumeric() function
numpy.core.defchararray.isnumeric(arr) function returns true for each element if there are only numeric characters and there is at least one character.It returns false otherwise. Parameters: arr : array_like of str or unicode. Returns : [ndarray] Output array of bools. Code #1 : # Python program explaining # numpy.char.isnumeric() method import num
1 min read
numpy string operations | isdigit() function
numpy.core.defchararray.isdigit(arr) function returns True for each element if all characters in the string are digits and there is at least one character; returns false otherwise. Parameters: arr : array_like of str or unicode. Returns : [ndarray] Output array of bools. Code #1 : # Python program explaining # numpy.char.isdigit() method import num
1 min read
numpy string operations | isdecimal() function
numpy.core.defchararray.isdecimal(arr) function returns True for each element if there are only decimal characters in the element.It returns false otherwise. Parameters: arr : array_like of str or unicode. Returns : [ndarray] Output array of bools. Code #1 : # Python program explaining # numpy.char.isdecimal() method import numpy as geek # input ar
1 min read
numpy string operations | isalpha() function
numpy.core.defchararray.isalpha(arr) function returns True for each element if all characters in the string are alphabetic and there is at least one character; returns false otherwise. Parameters: arr : array_like of str or unicode. Returns : [ndarray] Output array of bools. Code #1 : # Python program explaining # numpy.char.isalpha() method import
1 min read
numpy string operations | swapcase() function
numpy.core.defchararray.swapcase(arr) function return element-wise a copy of the string with uppercase characters converted to lowercase and lowercase characters converted to uppercase. Syntax: numpy.char.swapcase(arr) Parameters: arr : [ array_like ] Input array which may be str or unicode. Returns : [ndarray] Output lowercased array of str or uni
1 min read
numpy string operations | isspace() function
numpy.core.defchararray.isspace(arr) function returns true for each element if there are only whitespace characters in the string and there is at least one character.It returns false otherwise. Syntax: numpy.core.isspace(arr) Parameters: arr : array_like of str or unicode. Returns : [ndarray] Output array of bools. Code #1 : # Python program explai
2 min read
numpy string operations | rstrip() function
numpy.core.defchararray.rstrip(arr, chars=None) is another function for doing string operations in numpy. It returns a copy with the trailing characters removed for each element in arr. Parameters: arr : array_like of str or unicode. char : [str or unicode, optional] the set of characters to be removed. If omitted or None, it removes whitespace. Th
2 min read
Article Tags :
Practice Tags :