I’m given a 20*122 matrix p. Each row of matrix is a 20-element vector. I want to calculate the distance between each vector and form a distance matrix. Here’s my code
mul = []
for i in 1:size(p,1)
push!(mul,norm(p[1,:]-p[i,:]))
end
mul = transpose(tiedrank(mul))
for i in 2:size(p,1)
for j in 1:size(p,1)
mul2 = []
push!(mul2,norm(p[i,:]-p[j,:]))
end
mul = vcat(mul,tiedrank(mul2)')
end
mul
Inside the j loop you create a local variable mul2, which isn’t accessible outside the loop. And even if it was, you reset it in every iteration. I would move the mul2 = [] up one line as a first step.
mul = []
for i in 1:size(p,1)
push!(mul,norm(p[1,:]-p[i,:]))
end
mul = transpose(tiedrank(mul))
for i in 2:size(p,1)
for j in 1:size(p,1)
mul2 = []
push!(mul2,norm(p[i,:]-p[j,:]))
end
mul = vcat(mul,tiedrank(mul2)')
end
mul
But the value of elements in matrix are incorrect.
Here is a more explicit hint of what @gustaphe is saying:
function test()
broader_scope = Int64[] # you should type your containers, as an aside
for j in 1:10
narrower_scope = Int64[]
push!(broader_scope, j)
push!(narrower_scope, j)
end
# One of the two objects between broader_scope and narrower_scope can be used
# here outside of the loop. Try uncommenting each of these lines and calling
# the test() function.
# @show broader_scope
# @show narrower_scope
end