生成一个在特定位置为1的向量如何实现?

huangapple go评论59阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月29日 18:14:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356459.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定