在Python中定义具有s个分量的单位向量

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

Define unit vector in Python with s components

问题

我想在Python中定义一个列向量v = (0, 0, …, 0, 1)。该向量应该有s个分量(对于任意的s),因此前s-1个分量应该为0,最后一个分量为1。我该如何做呢?因为s是任意的。提前感谢您的帮助!

正如我所说,我想使用np.array,但是s是任意的,所以我不知道如何使用np.array(因为分量的数量尚不清楚)。

英文:

I want to define a column vector v = (0, 0, …, 0, 1) in Python. The vector is supposed to have s components (for an arbitrary s), so the first s-1 components are supposed to be 0 and the last component 1. How do I do it? Because s is arbitrary. Thank you for your help in advance!

As I said, I wanted do use np.array but s is arbitrary. so I do not know how to use the np.array thingie (since the amount of components is not clear yet)

答案1

得分: 1

numpy.repeat 是一个选项:

s = 10

v = np.repeat([0, 1], 
展开收缩
)

输出:array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1])

您可以推广到任意数量的值:

# 一个 "1",零 "2",三个 "3",两个 "4"
np.repeat([1, 2, 3, 4], [1, 0, 3, 2])
# array([1, 3, 3, 3, 4, 4])
英文:

numpy.repeat is one option:

s = 10

v = np.repeat([0, 1], [s-1, 1])

Output: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1])

You can generalize to any number of values:

# one "1", zero "2", three "3", two "4"
np.repeat([1, 2, 3, 4], [1, 0, 3, 2])
# array([1, 3, 3, 3, 4, 4])

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

发表评论

匿名网友

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

确定