matlab中训练样本随机打乱的方法

来源:互联网 发布:单片机的发展趋势 编辑:程序博客网 时间:2024/04/30 09:35

使用randperm(),产生随机种子,然后交换位置,达到随机抽取样本的目的。

官方内容:

Matlab自带函数randperm(n)产生1到n的整数的无重复的随机排列,利用它就可以得到无重复的随机数。
function p = randperm(n);
%RANDPERM Random permutation.
% RANDPERM(n) is a random permutation of the integers from 1 to n.
% For example, RANDPERM(6) might be [2 4 5 6 1 3].
%
% Note that RANDPERM calls RAND and therefore changes RAND's state. %
% See also PERMUTE. % Copyright 1984-2002 The MathWorks, Inc.
% $Revision: 5.10 $ $Date: 2002/04/09 00:26:14 $
[ignore,p] = sort(rand(1,n));


原理:
1. rand(1, n)产生1行n列的0-1之内的随机数矩阵。
2. sort()把这个矩阵排序,返回的ignore是排序后的序列,p是排序后的序列的各数原来的索引,这个索引肯定是随机的,而且是在1到n间无重复的整数。


上代码:

>> a = rand(10,4)a =    0.9516    0.3015    0.0326    0.6448    0.9203    0.7011    0.5612    0.3763    0.0527    0.6663    0.8819    0.1909    0.7379    0.5391    0.6692    0.4283    0.2691    0.6981    0.1904    0.4820    0.4228    0.6665    0.3689    0.1206    0.5479    0.1781    0.4607    0.5895    0.9427    0.1280    0.9816    0.2262    0.4177    0.9991    0.1564    0.3846    0.9831    0.1711    0.8555    0.5830>> RandIndex = randperm( length( a ) );   % 随即打乱数组索引a = a( RandIndex,: );   % 用新的索引构造打乱后的数组>> aa =    0.9831    0.1711    0.8555    0.5830    0.9516    0.3015    0.0326    0.6448    0.7379    0.5391    0.6692    0.4283    0.9203    0.7011    0.5612    0.3763    0.9427    0.1280    0.9816    0.2262    0.4177    0.9991    0.1564    0.3846    0.0527    0.6663    0.8819    0.1909    0.5479    0.1781    0.4607    0.5895    0.2691    0.6981    0.1904    0.4820    0.4228    0.6665    0.3689    0.1206


0 0
原创粉丝点击