如何在MATLAB中从N个点中随机选择k个点? [英] How do I randomly select k points from N points in MATLAB?

查看:1304
本文介绍了如何在MATLAB中从N个点中随机选择k个点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码创建和绘制N点:

I use this code to create and plot N points:

N=input('No. of Nodes:');
data = rand(N,2) % Randomly generated n no. of nodes
x = data(:,1);
y = data(:,2);
plot(x,y,'*');

如何从N点中选择k点(概率为p=0.25),然后将这些k点涂成红色,而将其他点保留为*.

How do I choose k points (with probability p=0.25) out of N points, then color those k points red and leave the other points as *.

推荐答案

您可以采用两种方法.第一种解决方案是从N值中随机选择k值,这将确保您始终选择了k个点.第二种解决方案是随机选择值,每个值的平均选择概率为p,这可能导致随机选择的值小于0或多达N.

There are two approaches you can take. The first solution is to randomly pick k values from N values, which will ensure that you always have k points chosen. The second solution is to pick values randomly with each having an average probability p of being chosen, which could result in as little as 0 or as many as N being randomly chosen.

  • N值中选择k:

  • Picking k from N values:

您可以使用函数 RANDPERM 创建以下项的随机排列从1N的整数,然后在置换列表中选择第一个k值并将其重新绘制为红色:

You can use the function RANDPERM to create a random permutation of the integers 1 through N, then pick the first k values in the permuted list and replot them as red:

index = randperm(N);
plot(x(index(1:k)),y(index(1:k)),'r*');

  • 以平均概率p来选择值:

  • Picking values with an average probability p:

    您可以使用 RAND 函数从中选择随机值为每个N01,然后选择一个随机值小于或等于平均概率p的值,并将其重新绘制为红色:

    You can use the RAND function to pick a random value from 0 to 1 for each of your N values, then choose the ones with a random value less than or equal to your average probability p and replot them as red:

    index = (rand(N,1) <= p);
    plot(x(index),y(index),'r*');
    

  • 这篇关于如何在MATLAB中从N个点中随机选择k个点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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