matlab – 从稀疏矩阵中绘制一个随机的非零元素

我有一个稀疏的逻辑矩阵,它非常大.我想从中绘制随机的非零元素,而不将其所有非零元素存储在单独的向量中(例如,通过使用find命令).是否有捷径可寻?

目前我正在实施拒绝抽样,它正在绘制一个随机元素并检查它是否为非零.但是当非零元素的比例很小时,效率不高.

最佳答案 如果要选择随机位置,稀疏逻辑矩阵不是非常实用的数据表示.拒绝抽样和查找只是对我有意义的两种方式.以下是如何有效地完成它们(假设您想获得4个随机位置):

%# using find
idx = find(S);
%# draw 4 without replacement
fourRandomIdx = idx(randperm(length(idx),4));
%# draw 4 with replacement
fourRandomIdx = idx(randi(1,length(idx),4));
%# get row, column values
[row,col] = ind2sub(size(S),fourRandomIdx);



%# using rejection sampling
density = nnz(S)/prod(size(S));
%# estimate how many samples you need to get at least 4 hits
%# and multiply by 2 (or 3)
n = ceil( 1 / (1-(1-density)^4) ) * 2;
%# random indices w/ replacement
randIdx = randi(1,n,prod(size(S)));
%# identify the first four non-zero elements
[row,col] = find(S(randIdx),4,'first');
点赞