Concerning the following situation: max \forall i { h_i * X_{mij} }
Is there a function to obtain the maximal value between the product of two lists?
Concerning the following situation: max \forall i { h_i * X_{mij} }
Is there a function to obtain the maximal value between the product of two lists?
This?
julia> h = rand(10); x = rand(10,10,10);
julia> m = 2; j = 3;
julia> maximum(h .* x[m,:,j]) # note the dot in .* : element-wise multiplication
0.6705150233027053
julia> maximum(h[i] * x[m,i,j] for i in eachindex(h))
0.6705150233027053
The second won´t allocate intermediate arrays which are allocated in the first.
I’d also like to point out the generic version of this, reduce
, which I think is easier to remember than the difference between max
and maximum
. reduce(max, (h[i] * x[m, i, j] for i in eachindex(h)))
does the same thing, but works for generic “reducing” functions (functions that can take a collection and summarize it into one number). For example, reduce(+, array)
will take an array and return the sum.
TensorCast.jl is a friend:
using TensorCast
maximum(@cast _[i] := h[i] * x[$m,i,$j])
TensorCast is still a friend, with the @reduce
macro, if you want to make the calculation for all m
and j
:
using TensorCast
@reduce S[m,j] := maximum(i) h[i] * x[m,i,j]
For example:
julia> h = rand(3)
3-element Vector{Float64}:
0.8601614537887764
0.9085586312619703
0.5942727699394317
julia> x = rand(4,3,2)
4Ă—3Ă—2 Array{Float64, 3}:
[:, :, 1] =
0.350826 0.739942 0.565042
0.751966 0.430443 0.293777
0.714827 0.974151 0.680083
0.752213 0.289802 0.784696
[:, :, 2] =
0.95478 0.0218679 0.652646
0.308032 0.499596 0.724832
0.426453 0.865667 0.790571
0.370235 0.494717 0.53362
julia> @reduce S[m,j] := maximum(i) h[i] * x[m,i,j]
4Ă—2 Matrix{Float64}:
0.672281 0.821265
0.646812 0.453912
0.885073 0.786509
0.647025 0.44948
julia> S[1,1]
0.672280575421645
julia> S[1,1] == h[2]*x[1,2,1]
true
The computation for single (m,j) could be also written as:
@reduce _ := maximum(i) h[i] * x[$m,i,$j]
Dear colleagues, many thanks to you for you support.