如何在MATLAB中从N个点中随机选择k个点?

编程入门 行业动态 更新时间:2024-10-18 12:30:30
本文介绍了如何在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 创建以下项的随机排列从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个点?

    本文发布于:2023-11-29 12:40:09,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1646420.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:如何在   MATLAB   个点中

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!