【发布时间】:2014-09-15 18:18:23
【问题描述】:
我有一个数据集 (Data),它是一个包含 1000 个实数的向量。我想从 Data 中随机提取 100 乘以 10 个连续数字。我不知道如何为此目的使用 Datasample。 提前感谢您的帮助。
【问题讨论】:
标签: arrays matlab random random-sample
我有一个数据集 (Data),它是一个包含 1000 个实数的向量。我想从 Data 中随机提取 100 乘以 10 个连续数字。我不知道如何为此目的使用 Datasample。 提前感谢您的帮助。
【问题讨论】:
标签: arrays matlab random random-sample
你只能在 1 到 991 之间选择 100 个随机数:
I = randi(991, 100, 1)
然后将它们作为起点来索引 10 个连续元素:
cell2mat(arrayfun(@(x)(Data(x:x+9)), I, 'uni', false))
【讨论】:
这里有一个片段,但我没有使用 Datasample,而是使用randi 生成随机索引。
n_times = 100;
l_data = length(Data);
index_random = randi(l_data-9,n_times,1); % '- 9' to not to surpass the vector limit when you read the 10 items
for ind1 = 1:n_times
random_number(ind1,:) = Data(index_random(ind1):index_random(ind1)+9)
end
【讨论】:
random_number 预先分配为zeros(n_times,10)。获取10 元素不是+9 而不是+10?
这类似于Dan's answer,但避免使用单元格和arrayfun,因此可能更快。
让Ns 表示您想要的连续数字的数量(在您的示例中为 10),并让Nt 表示次数(在您的示例中为 100)。那么:
result = Data(bsxfun(@plus, randi(numel(Data)-Ns+1, Nt, 1), 0:Ns-1)); %// Nt x Ns
【讨论】:
这是另一个解决方案,接近@Luis,但使用cumsum 而不是bsxfun:
A = rand(1,1000); % The vector to sample
sz = size(A,2);
N = 100; % no. of samples
B = 10; % size of one sample
first = randi(sz-B+1,N,1); % the starting point for all blocks
rand_blocks = A(cumsum([first ones(N,B-1)],2)); % the result
这会产生一个 N×B 矩阵 (rand_blocks),它的每一行都是一个样本。当然,这可能是单行的,但它不会使它更快,我想保持清楚。对于较小的N 或B,此方法稍快一些。如果N 或B 变得非常大,那么bsxfun 方法会稍微快一些。此排名不受A大小的影响。
【讨论】: