How to Select Random Rows from a Matrix in MATLAB?
Last Updated :
09 Nov, 2022
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:
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
a = magic(5);
rand_row1 = a(randi(5),:);
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
a = magic(5);
rr1 = randi(5);
rand_row1 = a(rr1,:);
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
Share your thoughts in the comments
Please Login to comment...