如何在MATLAB中从N个点中随机选择k个点? [英] How do I randomly select k points from N points in MATLAB?
问题描述
我使用以下代码创建和绘制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
fromN
values:
您可以使用函数 RANDPERM 创建以下项的随机排列从1
到N
的整数,然后在置换列表中选择第一个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 函数从中选择随机值为每个N
值0
至1
,然后选择一个随机值小于或等于平均概率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屋!