# Matrix view based on BitVector?

**URL:** https://discourse.julialang.org/t/matrix-view-based-on-bitvector/126922
**Category:** Performance
**Created:** [March 13, 2025, 3:07pm UTC](https://discourse.julialang.org/t/matrix-view-based-on-bitvector/126922 "2025-03-13T15:07:07Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![AdaemmerP](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/adaemmerp/32/52351_2.png) [@AdaemmerP](https://discourse.julialang.org/u/AdaemmerP)
#### Post date: [March 13, 2025, 3:07pm UTC](https://discourse.julialang.org/t/matrix-view-based-on-bitvector/126922/1 "2025-03-13T15:07:07Z")

</div>

I have a pre-allocated BitVector that fills randomly inside a loop. Based on that BitVector, I want to create a view of a Matrix but it allocates. Is there a workaround?

A simple example:

```julia
using Chairmarks
ix = BitVector(zeros(10)) # values change
x = rand(10, 10) # stays fixed

ix .= bitrand(10)
@b @views $x[$ix, $ix] 
58.412 ns (4 allocs: 224 bytes)

```

---

<div class="post-metadata">

### Author: ![mbauman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mbauman/32/31082_2.png) [@mbauman](https://discourse.julialang.org/u/mbauman)
#### Post date: [March 13, 2025, 3:15pm UTC](https://discourse.julialang.org/t/matrix-view-based-on-bitvector/126922/2 "2025-03-13T15:15:17Z")

</div>

See:

> [@Shouldn't \`@views sum(data\[mask\])\` be non-allocating?](https://discourse.julialang.org/t/shouldnt-views-sum-data-mask-be-non-allocating/118135):
>
> I was surprised to see the following function allocates - is this expected? using BenchmarkTools function f\_viewalloc(data, mask) @views sum(data[mask]) end let N = 1\_000\_000 data = fill(true, N) mask = fill(true, N) @btime f\_viewalloc($data, $mask) end 1.476 ms (2 allocations: 7.63 MiB)
