Open In App

Manipulating matrices in Julia

Matrices in Julia are the heterogeneous type of containers and hence, they can hold elements of any data type. It is not mandatory to define the data type of a matrix before assigning the elements to the matrix. Julia automatically decides the data type of the matrix by analyzing the values assigned to it. Because of the ordered nature of a matrix, it makes it easier to perform operations on its values based on their index.

Following are some common matrix manipulation operations in Julia:



Creating a matrix

Julia provides a very simple notation to create matrices. A matrix can be created using the following notation: A = [1 2 3; 4 5 6]. Spaces separate entries in a row and semicolons separate rows. We can also get the size of a matrix using size(A).



Transpose of a matrix

Flipping a matrix:

Example 1: Flipping vertically




# Defining a rectangular matrix of size (2, 3)
B = [1 2 3; 4 5 6]    
  
# Flipping the matrix vertically
reverse(B, dims = 1)   

Output:

Example 2: Flipping horizontally




# Flipping the matrix horizontally
reverse(B, dims = 2)   

Concatenating matrices

Example 1: Concatenate to the side




# Creating a square matrix of size (2, 2)
A = [1 2; 3 4]        
  
# Creating a rectangular matrix of size (2, 3)
B = [5 6 7; 8 9 10]   
hcat(A, B)

Example 2: Concatenate to the bottom




# Creating a square matrix of size (3, 2)
A = [1 2;3 4; 5 6]        
  
# Creating a rectangular matrix of size (4, 2)
B = [5 7;8 9; 10 11;14 16]   
vcat(A, B)

Reshaping a matrix


We can reshape a matrix into another matrix of different size.
Example 1: Reshaping a matrix




# The original matrix with size (3, 2)
A = [1 2; 3 4; 5 6]    

  • Output:
  • Reshaping the matrix to size (2, 3)




    reshape(A, (2, 3))
    
    

    Output:

    Reshaping the matrix to size (6, 1)




    reshape(A, (6, 1))
    
    

    Reshaping the matrix to size (1, 6)




    reshape(A, (1, 6))
    
    

    Output:

    Inverse of a matrix

    Article Tags :