我有以下矩阵:
M =[ 0 0 0 0 0 0 0 0 ;
0 0 0 0 0 0 6 0 ;
0 0 0 0 3 0 3 3 ;
0 0 0 9 9 6 9 6 ;
0 0 0 9 6 9 9 0 ;
0 0 0 0 6 3 0 0 ;
0 0 0 0 0 0 0 0 ;
0 0 0 0 0 0 0 0 ];
我希望在1
的10个随机选择的元素中添加M
,其中0
大于DECLARE @fileLocation VARCHAR(128) = 'c:\foldername\'
--DECLARE @fileName VARCHAR(128)
---------------------------------------------------------------------------------------------------------------
--Get a list of all the file names in the directory
---------------------------------------------------------------------------------------------------------------
IF OBJECT_ID('tempdb..#FileNames') IS NOT NULL DROP TABLE #FileNames
CREATE TABLE #FileNames (
id int IDENTITY(1,1)
,subdirectory nvarchar(512)
,depth int
,isfile bit
,LogTime datetime null)
INSERT #FileNames (subdirectory,depth,isfile)
EXEC xp_dirtree @fileLocation, 1, 1
。
怎么做?
答案 0 :(得分:3)
查找大于零的元素的索引,并从那些将递增的索引生成n
个随机样本。然后,只需将1
添加到n
个随机索引的元素中。
n=10; %No. of elements of M greater than zero which will be incremented by 1
t1 = find(M>0); %Finding indices of elements of M which are greater than zero
t2 = randperm(length(t1)); %Generating random indices from which first n will be selected
M(t1(t2(1:n))) = M(t1(t2(1:n)))+1 %Incrementing elements of random n indices
如果您有统计和机器学习工具箱,则可以使用以下更简单的方法
解决方案使用randsample
:
n=10;
temp = randsample(find(M>0),n);
M(temp) = M(temp)+1
答案 1 :(得分:2)
您可以通过创建非零元素位置的随机排列来选择要增加的元素。
m = 10; % we want to increment 10 elements
elements = find(M); % positions of the nonzero elements
rand_order = randperm(numel(elements), m); % generate random permutation
M(elements(rand_order)) = M(elements(rand_order)) + 1;
randperm
确保每个非零元素只能以随机顺序选择一次。