@@ -241,16 +241,47 @@ Another common way of storing the same data is as a 3×`N` `Matrix{Float64}`.
241
241
Rather conveniently, such types have * exactly* the same binary layout in memory,
242
242
and therefore we can use ` reinterpret ` to convert between the two formats
243
243
``` 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))
247
248
end
248
249
```
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
+ ```
254
285
255
286
### Working with mutable and immutable arrays
256
287
0 commit comments