You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Suppose we have a position vector `r = [:x, :y, :z]` which is naturally one-based, ie. `r[1] == :x`, `r[2] == :y`, `r[3] == :z` and we also want to cosntruct a relativistic position vector which includes time as the 0th component. This can be done with OffsetArrays like
25
+
```julia
26
+
julia>using OffsetArrays
27
+
28
+
julia> r = [:x, :y, :z];
29
+
30
+
julia> x =OffsetVector([:t, r...], 0:3)
31
+
OffsetArray(::Array{Symbol,1}, 0:3) with eltype Symbol with indices 0:3:
32
+
:t
33
+
:x
34
+
:y
35
+
:z
36
+
37
+
julia> x[0]
38
+
:t
39
+
40
+
julia> x[1:3]
41
+
3-element Array{Symbol,1}:
42
+
:x
43
+
:y
44
+
:z
45
+
```
46
+
47
+
## Example: Polynomials
48
+
Suppose one wants to represent the Laurent polynomial
49
+
```
50
+
6/x + 5 - 2*x + 3*x^2 + x^3
51
+
```
52
+
in julia. The coefficients of this polynomial are a naturally `-1` based list, since the `n`th element of the list
53
+
(counting from `-1`) `6, 5, -2, 3, 1` is the coefficient corresponding to the `n`th power of `x`. This Laurent polynomial can be evaluated at say `x = 2` as follows.
OffsetArray(::Array{Int64,1}, -1:3) with eltype Int64 with indices -1:3:
59
+
6
60
+
5
61
+
-2
62
+
3
63
+
1
64
+
65
+
julia>polynomial(x, coeffs) =sum(coeffs[n]*x^n for n ineachindex(coeffs))
66
+
polynomial (generic function with 1 method)
67
+
68
+
julia>polynomial(2.0, coeffs)
69
+
24.0
70
+
```
71
+
Notice our use of the `eachindex` function which does not assume that the given array starts at `1`.
72
+
23
73
## Notes on supporting OffsetArrays
24
74
25
75
Julia supports generic programming with arrays that doesn't require you to assume that indices start with 1, see the [documentation](http://docs.julialang.org/en/latest/devdocs/offset-arrays/).
0 commit comments