I think my problem is fairly simple.
a = [[1,2], [3,4,5], 10]
b = [[2,3], [4,5,6], 1]
c = [a,b]
I want to find the index where the last element is the smallest. In the example, the value is 1, and it should return 2.
I tried to use the “findmin()”, but I simply didn’t know how to access the last element of each row.
Is only “for” possible to achieve this?
lrnv
March 5, 2023, 8:34am
2
Can’t you use the keyword by=last
? Check the documentation of findmin
for the correct syntax.
2 Likes
Thank you very much for your reply. What if I wanted to collect only the last elements from “c”?
lrnv
March 5, 2023, 8:44am
4
You request is unclear. There is also argmin
that you may be able to use.
1 Like
The way I’ve thought is as follows
# collect only the last element of each row of the vector c.
collection = Any[]
for (i,element) in enumerate(c)
push!(collection,element)
end
# find the index where the last element is the smallest
ind = findmin(collection)
# return the row of c that contains the smallest last element
c[ind]
lrnv
March 5, 2023, 9:11am
6
Try findmin(c,by=last)
You may also try broadcasting as collection=last.(c)
1 Like
findmin
doesn’t seem to support a by
keyword. The syntax for that seems to be findmin(last, c)
.
3 Likes
Just in case someone finds this thread helpful, I tried both.
Thank you so much everyone for the suggestions!
a = [[1,2], [3,4,5], 10]
b = [[2,3], [4,5,6], 1]
c = [a,b]
findmin(last,c)
(1, 2)
a = [1, [1,2], [3,4,5], 10]
b = [2, [3,3], [1,1,1], 20]
c= [a,b]
findmin(c,by=last)
MethodError: no method matching findmin(::Vector{Vector{Any}}; by=last)
Closest candidates are:
findmin(::AbstractArray; dims) at reducedim.jl:1112 got unsupported keyword argument "by"
findmin(::Any) at reduce.jl:977 got unsupported keyword argument "by"
findmin(::Any, !Matched::SparseArrays.AbstractSparseVector{T}) where T at /Applications/Julia-1.8.5.app/Contents/Resources/julia/share/julia/stdlib/v1.8/SparseArrays/src/sparsevector.jl:1432 got unsupported keyword argument "by"
...
Stacktrace:
[1] kwerr(::NamedTuple{(:by,), Tuple{typeof(last)}}, ::Function, ::Vector{Vector{Any}})
@ Base ./error.jl:165
[2] top-level scope
@ ~/Documents/Migration/Julia Code/Quantitative (simple)/W SMM BF (March 4).ipynb:6