📜  如何在 MATLAB 中随机排列矩阵中的列?

📅  最后修改于: 2022-05-13 01:55:13.854000             🧑  作者: Mango

如何在 MATLAB 中随机排列矩阵中的列?

在本文中,我们将在size()randperm()函数的帮助下讨论“矩阵中列的随机洗牌”。 size()函数用于返回指定数组“X”的每个维度的大小或指定矩阵“X”的大小。

使用 Size() 和 randperm()

1) randperm(): randperm()函数用于整数的随机排列。

这里,

randperm(n)返回一个行向量,其中包含从“1”到“n”的整数的随机排列,没有任何重复。

randperm(n,k)返回一个行向量,其中包含“k”多个从 1 到 n 随机选择的唯一整数。

参数:此函数接受两个参数。

  • n:这是指定的数字,从“1”生成一个随机数,没有任何重复。
  • k:它是从 1 到 n 中随机选择的唯一整数的数量。

例子:

Matlab
% MATLAB code for calling the randperm()
% to generate a random permutation
% of the integers from 1 to 5
A = randperm(5)


Matlab
% MATLAB code for size() and randpem()
% Specifying a 3*3 matrix
A = [1 2 3
     4 5 6
     7 8 9];
      
% Calling the size() function over
% the above matrix which gives a row vector
% whose elements are the lengths of the
% corresponding dimensions of A
cols = size(A);
 
% Calling the randperm() function for the
% random permutation of the above matrix
% over its dimension of 3*3
P = randperm(cols);
 
% Getting the column wise randomly shuffled matrix
B = A(:,P)


Matlab
% MATLAB code for shuffle 4*4 matrix
% using randperm()
% Specifying a 4*4 matrix
A = [1 2 3 4
     5 6 7 8
     9 10 11 12
     13 14 15 16];
      
% Calling the randperm() function to
% randomly shuffle the column of matrix A
A(:, randperm(size(A, 2)))


输出:

A =
  4   2   3   1   5

下面的例子是“矩阵中列的随机改组”,可以使用size()randperm()函数的组合来完成:



2) size: size()函数用于返回指定数组“X”各维度的大小或指定矩阵“X”的大小。

这里,

size(X)返回具有 ndims(X) 元素的向量 d 中指定数组“X”的每个维度的大小。

[m,n] = size(X)在单独的变量 m 和 n 中返回指定矩阵“X”的大小。

size(X,dim)返回由标量 dim 指定的“X”维度的大小。

[d1,d2,d3,...,dn] = size(X)返回单独变量中指定数组“X”的前 n 个维度的大小。

参数:此函数接受两个参数,如下所示:

  • X:它是指定的数组或矩阵或维度。
  • dim:它是指定维度“X”的标量值

示例 1:

MATLAB

% MATLAB code for size() and randpem()
% Specifying a 3*3 matrix
A = [1 2 3
     4 5 6
     7 8 9];
      
% Calling the size() function over
% the above matrix which gives a row vector
% whose elements are the lengths of the
% corresponding dimensions of A
cols = size(A);
 
% Calling the randperm() function for the
% random permutation of the above matrix
% over its dimension of 3*3
P = randperm(cols);
 
% Getting the column wise randomly shuffled matrix
B = A(:,P)

输出:

B =
  3   1   2
  6   4   5
  9   7   8

示例 2:

MATLAB

% MATLAB code for shuffle 4*4 matrix
% using randperm()
% Specifying a 4*4 matrix
A = [1 2 3 4
     5 6 7 8
     9 10 11 12
     13 14 15 16];
      
% Calling the randperm() function to
% randomly shuffle the column of matrix A
A(:, randperm(size(A, 2)))

输出: