如何从单元格数组中抽取随机样本? [英] how can I take a random sample from a cell array?

查看:100
本文介绍了如何从单元格数组中抽取随机样本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在matlab中有一个单元格数组,我需要随机抽取一个样本,但是matlab中的randsample()函数似乎不适用于单元格数组.我可以使用randi()生成随机数,这很好,但是我只需要唯一的数字.

I have a cell array in matlab and I need to take a random sample, however the randsample() function in matlab appears not to work on cell arrays. I can generate random numbers using randi() which is fine, however I want only unique numbers.

是否有一个函数可以用来从单元格数组中随机采样,或者有人可以向我展示如何使用randi()生成唯一数字吗?

Is there a function that can be used to randomly sample from a cell array, or can anyone show me how to generate unique numbers using randi()?

非常感谢.

推荐答案

您可以使用randperm函数,该函数生成随机排列而无需重复数字.

You can use the randperm function which generates a random permutation without repeat of the numbers.

例如P = randperm(N,K)给出K个唯一的,非重复的数字,介于1和N之间

For example P = randperm(N,K) gives K unique, non repeating numbers between 1 and N

randperm(10,5)给我:

9     2     1     6     5

randperm(10,10)给我:

7     9     4     8     2     3     6     5     1    10

假设您有一个单元格数组

Lets say you have a cell array

C = {'only','mad','dogs','and','englishmen','go','out','in','the','midday','sun'}

然后您可以生成一组随机短语,而无需重复这样的标记

Then you could generate a set of random phrases without repeating tokens like this

output=[];
for i=1:5
    output = [output;sprintf('%s ',C{randperm(length(C))})];
end

这给了我类似下面的输出

which gives me an output like the following

out only dogs in mad englishmen sun go and midday the 
in and the midday sun only englishmen out go dogs mad 
out midday go in dogs and only englishmen the mad sun 
the sun out mad midday englishmen go only and dogs in 
midday mad sun out dogs in and go englishmen the only 

这篇关于如何从单元格数组中抽取随机样本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆