How to delete a row of a matrix in Julia

A matrix in Julia is a multi-dimensional array of elements. It stores elements as rows and columns. A matrix can store elements of multiple data types. It can even hold duplicate values.

There is no default method to delete a row from a matrix in Julia. Here, we'll use slicing and copy methods to create a new matrix without a specific row.

Example

matrix = [1 2 ;3 4; 5 6; 7 8; 9 10], row_index = 3

Output: [1 2 ;3 4; 7 8; 9 10]

Example showing how to delete a row at index 3 from the matrix

Syntax

Here is the syntax for the method:

vcat( matrix[1:row_index-1,:], matrix[row_index+1:size(matrix)[1], :])

Parameters

  • vcat(): This function takes two matrices as parameters. It will copy the second matrix into the first matrix.

Here, we get two slices of matrices and create a new matrix based on them using the vcat() function. The steps are as follows:

  • Get the first slice of the matrix from the first row to the row before row_indexindex of a row that we delete.

  • Get the second slice of the matrix from the row after the row_index till the end of the matrix.index of a row that we delete

Let's take a look at an example of this.

Code example

#given matrix
matrix = [1 2 ;3 4; 5 6; 7 8; 9 10]
#given row index to delete from the matrix
row_index = 3
#delete row at a given index
display(vcat( matrix[1:row_index-1,:], matrix[row_index+1:size(matrix)[1], :]))

Code explanation

In the above code snippet, we have the following:

  • Line 2: We declare and initialize a 5x2 matrix and assign it to a variable matrix.

  • Line 5: We assign the row index to delete from the matrix to a variable row_index.

  • Line 8: We delete the row present at row_index in the matrix using the slicing and copy methods.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved