如何在 MATLAB 中从所有可能的行组合创建新矩阵?
在 MATLAB 中,矩阵不过是一个二维(二维)数字数组,排列成多行多列。矩阵是 MATLAB 编程中最基本的数据结构,用于存储和操作数据。
在本教程中,我们将学习如何在 MATLAB 中从所有可能的行组合创建一个新矩阵。为此,我们可以使用 MATLAB 的内置函数“randperm”。“randperm”函数将随机选择一个行索引并创建一个新矩阵。
算法
下面描述了从所有可能的行组合创建新矩阵的分步过程:
步骤 (1) − 指定输入矩阵或矩阵中的行数 (n) 和列数 (m)。
步骤 (2) − 创建一个 n × m 阶的输入矩阵。
步骤 (3) − 指定要随机选择的行数。
步骤 (4) − 从矩阵中获取选定的行索引。
步骤 (5) − 根据选定的行索引从输入矩阵中随机选择行。
步骤 (6) − 显示新创建的矩阵。
示例 (1):从给定矩阵中随机选择行创建矩阵
现在,让我们考虑几个 MATLAB 示例,以实际了解如何在 MATLAB 中从所有可能的行组合创建一个新矩阵。
% MATLAB program to create new matrix from all possible row combinations
% Specify the rows and columns of the input matrix
n = 4; % Row in given matrix
m = 3; % Columns in given matrix
% Generate a random matrix of order n x m
mat = rand(n, m);
% Specify the number of rows to be selected randomly
x = 2;
% Select row indices from the given matrix
i = randperm(n, x);
% Select rows randomly from the matrix
new_mat = mat(i, :);
% Display the input and new created matrices
disp('The given input matrix is:');
disp(mat);
disp('Randomly created new matrix is:');
disp(new_mat);
输出
The given input matrix is:
0.1656 0.6892 0.2290
0.6020 0.7482 0.9133
0.2630 0.4505 0.1524
0.6541 0.0838 0.8258
Randomly created new matrix is:
0.2630 0.4505 0.1524
0.6020 0.7482 0.9133
解释
此 MATLAB 代码生成一个新矩阵,其中每一行包含输入矩阵中所有可能的行组合。此代码的重要之处在于它将随机选择所有行,因此每次运行代码时,我们都会得到不同的结果。
示例 (2):从给定矩阵中随机选择所有行创建矩阵
% MATLAB Program to create a matrix by selecting all rows of given matrix randomly
% Define the size of the input matrix
n = 3; % Number of rows
m = 4; % Number of columns
% Create an input matrix
mat = [1 2 3 4; 5 9 2 1; 4 3 8 7];
% Randomly select row indices from the input matrix
i = randperm(n);
% Select rows from the input matrix randomly
new_mat = mat(i, :);
% Display the input matrix and new created matrix
disp('The given input matrix is:');
disp(mat);
disp('Randomly created new matrix is:');
disp(new_mat);
输出
The given input matrix is:
1 2 3 4
5 9 2 1
4 3 8 7
Randomly created new matrix is:
1 2 3 4
5 9 2 1
4 3 8 7
解释
此 MATLAB 代码接受给定的输入矩阵,并通过随机选择给定矩阵的所有行来创建一个新矩阵。因此,输出矩阵的行数和列数等于给定矩阵。
每次运行代码时,代码都会生成一个不同的结果矩阵,该矩阵是通过从输入矩阵中随机选择行创建的。
结论
在本教程中,我们解释了如何在 MATLAB 中从所有可能的行组合创建一个新矩阵。MATLAB 提供了几种执行此任务的方法,但我们已在本教程中解释了最简单的方法。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP