試圖想出一種快速的方法來確保 a 在 Julia 中是單調的。
我一直在使用的緩慢(且明顯)的方法是這樣的:
function check_monotonicity(
timeseries::Array,
column::Int
)
current = timeseries[1,column]
for row in 1:size(timeseries, 1)
if timeseries[row,column] > current
return false
end
current = copy(timeseries[row,column])
end
return true
end
所以它的作業原理是這樣的:
julia> using Distributions
julia>mono_matrix = hcat(collect(0:0.1:10), rand(Uniform(0.4,0.6),101),reverse(collect(0.0:0.1:10.0)))
101×3 Matrix{Float64}:
0.0 0.574138 10.0
0.1 0.490671 9.9
0.2 0.457519 9.8
0.3 0.567687 9.7
?
9.8 0.513691 0.2
9.9 0.589585 0.1
10.0 0.405018 0.0
julia> check_monotonicity(mono_matrix, 2)
false
然后是相反的例子:
julia> check_monotonicity(mono_matrix, 3)
true
有誰知道長時間序列執行此操作的更有效方法?
uj5u.com熱心網友回復:
你的實作肯定不慢!它幾乎是最佳速度。你絕對應該擺脫copy. 雖然矩陣元素只是普通資料時沒有什么壞處,但在其他情況下可能會很糟糕,BigInt例如。
這與您最初的努力很接近,但在索引和陣列型別方面也更加健壯:
function ismonotonic(A::AbstractMatrix, column::Int, cmp = <)
current = A[begin, column] # begin instead of 1
for i in axes(A, 1)[2:end] # skip the first element
newval = A[i, column] # don't use copy here
cmp(newval, current) && return false
current = newval
end
return true
end
另一個提示:您不需要使用collect. 事實上,您幾乎不應該使用 collect。改為執行此操作(我洗掉了Uniform,因為我沒有 Distributions.jl):
mono_matrix = hcat(0:0.1:10, rand(101), reverse(0:0.1:10)) # or 10:-0.1:0
或者這可能更好,因為您可以更好地控制范圍內的元素數量:
mono_matrix = hcat(range(0, 10, 101), rand(101), range(10, 0, 101))
然后你可以像這樣使用它:
1.7.2> ismonotonic(mono_matrix, 3)
false
1.7.2> ismonotonic(mono_matrix, 3, >=)
true
1.7.2> ismonotonic(mono_matrix, 1)
true
uj5u.com熱心網友回復:
在數學中,我們通常將一個序列定義為單調的,如果它是非遞減或非遞增的。如果這是您想要的,請執行以下操作:
issorted(view(mono_matrix, :, 2), rev=true)
檢查它是否不增加,并且:
issorted(view(mono_matrix, :, 2))
檢查它是否不減少。
如果您想要減少檢查,請執行以下操作:
issorted(view(mono_matrix, :, 3), rev=true, lt = <=)
用于減少,但將0.0and-0.0視為相等或
issorted(view(mono_matrix, :, 3), lt = <=)
增加,但0.0平等-0.0對待。
如果要區分0.0然后-0.0分別做:
issorted(view(mono_matrix, :, 3), rev=true, lt = (x, y) -> isequal(x, y) || isless(x, y))
issorted(view(mono_matrix, :, 3), lt = (x, y) -> isequal(x, y) || isless(x, y))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/440332.html
下一篇:狀態變數更改導致無限渲染回圈
