如何在 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