英文:
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])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论