Matlab-计算向量中每个元素的概率 [英] Matlab - computing the probability of each element within a vector

查看:323
本文介绍了Matlab-计算向量中每个元素的概率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量y,它可能具有以下形式:

I am having a vector y which may have the following form:

y = [1 1 1 1 2 2 2 2 1 1 3 3 4 5]

我想将概率附加到y中的每个元素,因为它是由随机变量生成的.在这种情况下,元素1的概率为6/14,元素2的概率为4/14,元素3的值为2/14,元素4和5的值为1/14.

And I want to attach a probability to each element within y as it would've been generated by a random variable. In this case, the element 1 would have the probability 6/14, the element 2 would have the probability 4/14, the element 3 the value 2/14 and the elements 4 and 5 the value 1/14.

基本上,结果应如下所示:

And basically, the result should look like:

prob_y = 1/14 * [6 6 6 6 4 4 4 4 6 6 2 2 1 1]

有没有没有任何forwhile循环的方法?

Is there a way of doing this without any for or while loops?

推荐答案

输入向量中的唯一元素可以使用 ARRAYFUN

The unique elements in your input vector can be determined using the UNIQUE function. You can then get the desired output using ARRAYFUN and an anonymous function that checks the number of each unique element in your input vector:


>> y = [1 1 1 1 2 2 2 2 1 1 3 3 4 5];
>> prob_y = arrayfun(@(x)length(find(y==x)), unique(y)) / length(y)

prob_y =

    0.4286    0.2857    0.1429    0.0714    0.0714

这篇关于Matlab-计算向量中每个元素的概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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