julia求矩阵小于某个数值的和

A = [2 3 4 5 6]
我想求矩阵中小于等于3的和,请问用哪个函数?

有很多方法,但直接写就非常快了,不需要任何“高级”的函数。

using BenchmarkTools
A = [2 3 4 5 6]

function foo1(A)
   sum(A[findall(<=(3), A)])
end

@btime foo1($A)

foo2(A) = sum(A[A .<= 3])

@btime foo2($A)

function foo3(A)
   s = 0
   for a in A
      if a <= 3
         s+=a
      end
   end
   s
end

@btime foo3($A)

f(x) = x <= 3 ? x : 0

@btime sum($f, $A)

Results:

207.222 ns (4 allocations: 336 bytes)
148.798 ns (3 allocations: 240 bytes)
6.900 ns (0 allocations: 0 bytes)
7.700 ns (0 allocations: 0 bytes)
3 个赞

膜拜大佬,受教了

也可以考虑使用数组推导。

julia> A=rand(3,3)
3×3 Matrix{Float64}:
 0.25722   0.190108  0.644836
 0.647474  0.337786  0.474499
 0.327734  0.386461  0.510107

julia> sum(a for a in A if a <0.3)
0.44732822821662

julia> @btime sum(a for a in $A if a <0.3)
  18.222 ns (0 allocations: 0 bytes)
0.44732822821662
2 个赞