Open In App

How to Select Random Rows from a Matrix in MATLAB?

Last Updated : 09 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A matrix is an n x n array that stores integers, floating point numbers or alphanumeric data in MATLAB. Indexing a matrix is the same as indexing an array.

 Syntax:

matrix_name(i,j)
where, i is the row number, and  J is the column number which is to be indexed.

Example 1: 

Matlab




% MATLAB code for select 
% random matrix elements 
mat = magic(5);
mat(2,5)


Output:

 

Selecting Random Rows From a Matrix:

We can use the randi() function to select random rows from a given matrix. 

Syntax:

randi(n)

It gets random integers from the range 1 to n. We will select two random rows from a magic square.

Example 2:

Matlab




% MATLAB code for select 
% random matrix elements in range
  
a = magic(5);
  
% Selecting random row 1
rand_row1 = a(randi(5),:);
  
% Selecting random row 2
rand_row2 = a(randi(5),:);


Output:

 

We can visually verify that the above program indexed the 5th and 4th rows of the magic square.

In case the user needs the row number of the random row selected, it can be done easily by storing the Randi value in a variable.

Example 3:

Matlab




% MATLAB code for select 
% random matrix raw elements 
a = magic(5);
  
% Selecting random row 1
rr1 = randi(5);
rand_row1 = a(rr1,:);
  
% Selecting random row 2
rr2 = randi(5);
rand_row2 = a(rr2,:);


Output:

 

This program will store the first random row number in rr1 and the second random row number in rr2. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads