I’m just wondering if there is a easier / better way to step thru the elements of a 10x2 matrix, where I want to get each part of the x2 as an element:
testmatrix = zeros(Int,10,2)
for tidx = 1:size(testmatrix)[1]
t1 = testmatrix[tidx,1]
t2 = testmatrix[tidx,2]
println("t1 = $t1 t2 = $t2")
end
In this admittedly dumb example, I want to treat each part of the “x2” as a 2 element vector.
One way:
julia> M = rand(0:9, 10, 2)
10×2 Matrix{Int64}:
7 1
6 0
6 0
6 9
8 3
9 1
4 9
1 5
2 5
9 9
julia> for i in axes(M, 1)
println(M[i, :])
end
[7, 1]
[6, 0]
[6, 0]
[6, 9]
[8, 3]
[9, 1]
[4, 9]
[1, 5]
[2, 5]
[9, 9]
eachrow
?
julia> A = rand(5,2)
5×2 Matrix{Float64}:
0.535485 0.39958
0.185981 0.821799
0.699819 0.355746
0.796002 0.640743
0.761191 0.513014
julia> collect(eachrow(A))
5-element Vector{SubArray{Float64, 1, Matrix{Float64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
[0.5354849094718778, 0.3995795322090717]
[0.1859805121916167, 0.8217989381641213]
[0.6998186399284567, 0.35574632769553527]
[0.7960020715211013, 0.6407429528950367]
[0.7611912194497008, 0.5130138680605387]
3 Likes