cb1*_*b14 1 arrays function julia
试图想出一种快速方法来确保 a 在 Julia 中是单调的。
\n我一直在使用的缓慢(且明显)的方法是这样的:
\nfunction check_monotonicity(\n timeseries::Array,\n column::Int\n)\n current = timeseries[1,column]\n for row in 1:size(timeseries, 1)\n if timeseries[row,column] > current \n return false\n end \n current = copy(timeseries[row,column])\n end \n return true\nend\nRun Code Online (Sandbox Code Playgroud)\n所以它的工作原理是这样的:
\njulia> using Distributions\n\njulia>mono_matrix = hcat(collect(0:0.1:10), rand(Uniform(0.4,0.6),101),reverse(collect(0.0:0.1:10.0)))\n101\xc3\x973 Matrix{Float64}:\n 0.0 0.574138 10.0\n 0.1 0.490671 9.9\n 0.2 0.457519 9.8\n 0.3 0.567687 9.7\n \xe2\x8b\xae \n 9.8 0.513691 0.2\n 9.9 0.589585 0.1\n 10.0 0.405018 0.0\njulia> check_monotonicity(mono_matrix, 2)\nfalse\nRun Code Online (Sandbox Code Playgroud)\n然后对于相反的例子:
\njulia> check_monotonicity(mono_matrix, 3)\ntrue\nRun Code Online (Sandbox Code Playgroud)\n有谁知道对于长时间序列来说更有效的方法?
\n你的执行速度肯定不慢!它几乎是最佳速度。你绝对应该摆脱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
Run Code Online (Sandbox Code Playgroud)
另一个提示:您不需要使用collect. 事实上,您几乎不应该使用collect。改为这样做(我删除了,Uniform因为我没有 Distributions.jl):
mono_matrix = hcat(0:0.1:10, rand(101), reverse(0:0.1:10)) # or 10:-0.1:0
Run Code Online (Sandbox Code Playgroud)
或者这可能更好,因为您可以更好地控制范围内的元素数量:
mono_matrix = hcat(range(0, 10, 101), rand(101), range(10, 0, 101))
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它:
1.7.2> ismonotonic(mono_matrix, 3)
false
1.7.2> ismonotonic(mono_matrix, 3, >=)
true
1.7.2> ismonotonic(mono_matrix, 1)
true
Run Code Online (Sandbox Code Playgroud)
在数学中,如果一个级数不减或不增,我们通常将其定义为单调的。如果这是您想要的,那么请执行以下操作:
issorted(view(mono_matrix, :, 2), rev=true)
Run Code Online (Sandbox Code Playgroud)
检查它是否不增加,并且:
issorted(view(mono_matrix, :, 2))
Run Code Online (Sandbox Code Playgroud)
检查它是否是非递减的。
如果您想要减少支票,请执行以下操作:
issorted(view(mono_matrix, :, 3), rev=true, lt = <=)
Run Code Online (Sandbox Code Playgroud)
减少,但将0.0和视为-0.0相等或
issorted(view(mono_matrix, :, 3), lt = <=)
Run Code Online (Sandbox Code Playgroud)
为增加,但平等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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
403 次 |
| 最近记录: |