Skip to content

Commit 1d881f3

Browse files
authored
Merge pull request #619 from JuliaArrays/cjf/reinterpret-docfix
Fix docs for reinterpret
2 parents 83e134a + 04922cd commit 1d881f3

File tree

1 file changed

+39
-8
lines changed

1 file changed

+39
-8
lines changed

docs/src/pages/api.md

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -241,16 +241,47 @@ Another common way of storing the same data is as a 3×`N` `Matrix{Float64}`.
241241
Rather conveniently, such types have *exactly* the same binary layout in memory,
242242
and therefore we can use `reinterpret` to convert between the two formats
243243
```julia
244-
function svectors(x::Matrix{Float64})
245-
@assert size(x,1) == 3
246-
reinterpret(SVector{3,Float64}, x, (size(x,2),))
244+
function svectors(x::Matrix{T}, ::Val{N}) where {T,N}
245+
size(x,1) == N || error("sizes mismatch")
246+
isbitstype(T) || error("use for bitstypes only")
247+
reinterpret(SVector{N,T}, vec(x))
247248
end
248249
```
249-
Such a conversion does not copy the data, rather it refers to the *same* memory
250-
referenced by two different Julia `Array`s. Arguably, a `Vector` of `SVector`s
251-
is preferable to a `Matrix` because (a) it provides a better abstraction of the
252-
objects contained in the array and (b) it allows the fast *StaticArrays* methods
253-
to act on elements.
250+
Such a conversion does not copy the data, rather it refers to the *same* memory.
251+
Arguably, a `Vector` of `SVector`s is often preferable to a `Matrix` because it
252+
provides a better abstraction of the objects contained in the array and it
253+
allows the fast *StaticArrays* methods to act on elements.
254+
255+
However, the resulting object is a Base.ReinterpretArray, not an Array, which
256+
carries some runtime penalty on every single access. If you can afford the
257+
memory for a copy and can live with the non-shared mutation semantics, then it
258+
is better to pull a copy by e.g.
259+
```julia
260+
function svectorscopy(x::Matrix{T}, ::Val{N}) where {T,N}
261+
size(x,1) == N || error("sizes mismatch")
262+
isbitstype(T) || error("use for bitstypes only")
263+
copy(reinterpret(SVector{N,T}, vec(x)))
264+
end
265+
```
266+
For example:
267+
```
268+
julia> M=reshape(collect(1:6), (2,3))
269+
2×3 Array{Int64,2}:
270+
1 3 5
271+
2 4 6
272+
273+
julia> svectors(M, Val{2}())
274+
3-element reinterpret(SArray{Tuple{2},Int64,1,2}, ::Array{Int64,1}):
275+
[1, 2]
276+
[3, 4]
277+
[5, 6]
278+
279+
julia> svectorscopy(M, Val{2}())
280+
3-element Array{SArray{Tuple{2},Int64,1,2},1}:
281+
[1, 2]
282+
[3, 4]
283+
[5, 6]
284+
```
254285

255286
### Working with mutable and immutable arrays
256287

0 commit comments

Comments
 (0)