英文:
How to generate a vector with ones at a certain place?
问题
I have a vector with ascending numbers like (2,3,6,10). Now I need to generate a second vector, where all entries in the called items are 1 and all others are 0, so (0,1,1,0,0,1,0,0,0,1).
我的尝试是:
原始数组
A = [2, 3, 6, 10]
创建一个最大值为A中最大值的零数组
B = zeros(Int, maximum(A))
将A中指定索引位置的元素设置为1
B[A] .= 1
问题在于这会导致一个四维的全为1的向量,而不是一个有10维的1和0的向量。我唯一的其他想法是使用for循环,但我想避免这样做。
英文:
I have a vector with ascending numbers like (2,3,6,10). Now I need to generate a second vector, where all entries in the called items are 1 and all others are 0, so (0,1,1,0,0,1,0,0,0,1).
My attempt was:
Original array
A = [2, 3, 6, 10]
Create a new array of zeros with the maximum value of A
B = zeros(Int, maximum(A))
Set the elements at the indices specified in A to 1
B[A] .= 1
The problem is this leads to a four-dimensional vector of ones instead of a 10-dimensional vector of ones and zeroes. The only other idea I have would be a for-loop which I would like to avoid
答案1
得分: 5
我认为你已经解决了这个问题。广播操作执行了你想要的操作,但返回了其他内容。
julia> A = [2, 3, 6];
julia> B = zeros(Int, maximum(A));
julia> B[A] .= 1
3-element view(::Vector{Int64}, [2, 3, 6]) with eltype Int64:
1
1
1
julia> B
6-element Vector{Int64}:
0
1
1
0
0
1
英文:
I think you've already solved this. The broadcasting operation does what you wanted, but returns something else.
julia> A = [2, 3, 6];
julia> B = zeros(Int, maximum(A));
julia> B[A] .= 1
3-element view(::Vector{Int64}, [2, 3, 6]) with eltype Int64:
1
1
1
julia> B
6-element Vector{Int64}:
0
1
1
0
0
1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论