Skip to content

Commit 85e2bcc

Browse files
authored
Merge pull request #106 from aytekinar/master
Change indexing of `Poly`s
2 parents 5ae3c9e + 223b5b6 commit 85e2bcc

File tree

2 files changed

+32
-13
lines changed

2 files changed

+32
-13
lines changed

src/Polynomials.jl

+26-12
Original file line numberDiff line numberDiff line change
@@ -206,23 +206,37 @@ transpose(p::Poly) = p
206206
* `getindex(p::Poly, i)`: If `p=a_n x^n + a_{n-1}x^{n-1} + ... + a_1 x^1 + a_0`, then `p[i]` returns `a_i`.
207207
208208
"""
209-
getindex{T}(p::Poly{T}, i) = (i+1 > length(p.a) ? zero(T) : p.a[i+1])
210-
getindex{T}(p::Poly{T}, idx::AbstractArray) = map(i->p[i], idx)
211-
function setindex!(p::Poly, v, i)
209+
getindex{T}(p::Poly{T}, idx::Int) = (idx length(p.a) ? zero(T) : p.a[idx+1])
210+
getindex{T}(p::Poly{T}, indices::AbstractVector{Int}) = map(idx->p[idx], indices)
211+
getindex{T}(p::Poly{T}, ::Colon) = p[0:length(p)-1]
212+
213+
function setindex!(p::Poly, value, idx::Int)
212214
n = length(p.a)
213-
if n < i+1
214-
resize!(p.a,i+1)
215-
p.a[n+1:i] = 0
215+
if n idx
216+
resize!(p.a, idx+1)
217+
p.a[n+1:idx] = 0
216218
end
217-
p.a[i+1] = v
218-
v
219+
p.a[idx+1] = value
220+
return p
219221
end
220-
function setindex!(p::Poly, vs, idx::AbstractArray)
221-
[setindex!(p, v, i) for (i,v) in zip(idx, vs)]
222-
p
222+
223+
function setindex!(p::Poly, values::AbstractVector, indices::AbstractVector{Int})
224+
for (idx, value) in zip(indices, values)
225+
setindex!(p, value, idx)
226+
end
227+
return p
223228
end
224-
eachindex{T}(p::Poly{T}) = 0:(length(p)-1)
225229

230+
function setindex!(p::Poly, value, indices::AbstractVector{Int})
231+
for idx in indices
232+
setindex!(p, value, idx)
233+
end
234+
return p
235+
end
236+
237+
setindex!(p::Poly, values, ::Colon) = setindex!(p, values, 0:length(p)-1)
238+
239+
eachindex{T}(p::Poly{T}) = 0:(length(p)-1)
226240

227241
copy(p::Poly) = Poly(copy(p.a), p.var)
228242

test/runtests.jl

+6-1
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,10 @@ p1[5] = 1
165165
@test p1[5] == 1
166166
@test p1 == Poly([1,2,1,0,0,1])
167167

168+
p1[:] = 0
169+
@test p1 zero(p1)
170+
p1[:] = [1,2,1,0,0,1]
171+
@test p1 == Poly([1,2,1,0,0,1])
168172

169173
## elementwise operations #52
170174
println("Test for element-wise operations")
@@ -187,6 +191,8 @@ p1 = Poly([4,5,6])
187191
p1[0:1] = [7,8]
188192
@test all(p1[0:end] .== [7,8,6])
189193

194+
@test p1[:] == coeffs(p1)
195+
190196
## conjugate of poly (issue #59)
191197
as = [im, 1, 2]
192198
bs = [1, 1, 2]
@@ -312,4 +318,3 @@ p2s = Poly([1], :s)
312318

313319
@test Poly([0.5]) + 2 == Poly([2.5])
314320
@test 2 - Poly([0.5]) == Poly([1.5])
315-

0 commit comments

Comments
 (0)