Create a Matrix by Selecting All Rows Randomly
Now we are creating a matrix by selecting all rows randomly. In this, we will declare a number of rows and columns and we create columns through another.
Below are the examples through which we can understand.
Syntax:
variable1 = rand(rows,columns); %make a matrix of nth rows and m columns.
variable2 = randperm(nth_rows); %select rows randomly
Explanation:- rand() command makes a matrix of rows and columns and randomly stores a number.
Example:
Matlab
% MATLAB code for create a matrix % randomly picking rows from a Matrix % size of given matrix i = 5; j = 6 ; A = rand(i,j) ; % select rwos randomly indx = randperm(i) ; iwant = A(indx,:) ; disp(iwant); |
Output:
Explanation:
In this, we are declaring i =5, j=6 ( number of rows and columns ) and we create columns through another. This means we are creating a matrix of possible row combinations and at last, we will display it on our screen.
How to Create a New Matrix From All Possible Row Combinations in MATLAB?
A matrix represents a collection of numbers arranged in an order of rows and columns. A matrix encloses the elements in parentheses or brackets. We will learn how to create a new matrix from all possible row combinations of rows of a different matrix and display the combinations.
Procedure of Making a Matrix:
- Declare the number of rows.
- Declare a number of columns
- Using the ‘rand’ function to pick random rows from a matrix.
- Select rows randomly
- Print matrix.
We can see the below examples to create a new matrix from all possible row combinations.
Syntax:
variable = randperm(parameter , parameter); %for taking random numbers
From the command randperm() it uses random numbers to make a matrix of row combinations.
Example:
Matlab
% MATLAB code to Create a matrix randomly % picking rows from a Matrix % size of given matrix i = 5; j = 4 ; a = rand(i,j) ; % pick rows from matrix a pick = 5 ; % select rows randomly id = randperm(i,pick) ; iwant = a(id,:) ; disp(iwant); |
Output:
Explanation:
In the above example, we are declaring the number of rows, and columns, and declaring a variable that stores random numbers and makes a matrix. In the above, we are taking random numbers in the matrix but we can also declare typically.