# Compute Distribution among binary vector

**URL:** https://discourse.julialang.org/t/compute-distribution-among-binary-vector/77792
**Category:** Performance
**Tags:** question
**Created:** [March 12, 2022, 3:26pm UTC](https://discourse.julialang.org/t/compute-distribution-among-binary-vector/77792 "2022-03-12T15:26:00Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![GoYetChallenged](https://avatars.discourse-cdn.com/v4/letter/g/87869e/32.png) [@GoYetChallenged](https://discourse.julialang.org/u/GoYetChallenged)
#### Post date: [March 12, 2022, 3:26pm UTC](https://discourse.julialang.org/t/compute-distribution-among-binary-vector/77792/1 "2022-03-12T15:26:00Z")

</div>

I want to compute marginal distributions among binary data.For example, I have several vectors like

```julia
a = [0, 1, 0, 1]
b = [1, 0, 0, 1]

```

and compute all possible distributions, like P(a=0, b=0) = 1/4, P(a=0, b=1) = 1/4, P(a=1, b=0) = 1/4, P(a=1, b=1) = 1/4. I code as followed

```julia
function marginal_distribution(data::Matrix, port::Vector)
    m, n = size(data)
    len = 2 ^ length(port)
    res = zeros(Float64, len)
    
    for i in 0:(len-1)
        tmp = ones(typeof(data[1]), m)
        
        for (j, cols) in enumerate(port)
            t = 1 - 1 & (i >> (j - 1))
            tmp .*= t .⊻ data[:, cols]
        end
        res[i+1] = mean(tmp)
    end
    return res
end

```

Each col of data represent a vector, and port is to choose the vector to be calculated. But this function is too slow. How can I acculate it?

---

<div class="post-metadata">

### Author: ![goerch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/goerch/32/29122_2.png) [@goerch](https://discourse.julialang.org/u/goerch)
#### Post date: [March 12, 2022, 8:21pm UTC](https://discourse.julialang.org/t/compute-distribution-among-binary-vector/77792/2 "2022-03-12T20:21:43Z")

</div>

Hi @GoYetChallenged,

> [@GoYetChallenged](#):
>
> But this function is too slow.

This question could be either directed at domain experts, which might introduce you to better algorithms, or at the general public. For the general understanding it might be better to post a complete M(inimal)W(orking)E(xample) and tell us why you think this function is too slow.
