你是对的基本行为。来自索引矩阵idx
的第一列的长度子向量用于从v
中选择元素,并且在首先通过标量theta
调整它们的值之后将它们放置在矩阵w
中的相同位置中。
使用基于一个索引的MATLAB和基于零的索引numpy
至关重要。
在MATLAB中,
clear
% Data matrices
w = zeros(5,5)
v = diag([10,20,30,40,50]) * ones(5,5)
% Indexing matrix
idx = ceil(5*rand(5, 5))
% Selection and adjustment parameters
p = 3
theta = 1
% Apply adjustment and selection
w(idx(1:p, 1), 1) = v(idx(1:p, 1), 1) - theta
产生输出
w =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
v =
10 10 10 10 10
20 20 20 20 20
30 30 30 30 30
40 40 40 40 40
50 50 50 50 50
idx =
3 1 2 3 4
1 1 2 1 3
4 1 2 2 2
1 1 5 1 1
1 2 4 5 4
theta =
1
p =
3
w =
9 0 0 0 0
0 0 0 0 0
29 0 0 0 0
39 0 0 0 0
0 0 0 0 0
而且,使用numpy
import numpy as np
# Data arrays
w = np.zeros((5,5))
v = np.dot(np.diag([10, 20, 30, 40, 50]), np.ones((5,5)))
print "w = "
print w
print "v = "
print v
# Indexing array
idx = np.floor(5 * np.random.rand(5,5)).astype(int)
print "idx = "
print idx
# Selection and adjustment parameters
theta = 1
p = 3
# Apply selection and adjustment
w[idx[:p, 0], 0] = v[idx[:p, 0], 0] - theta
print "w = "
print w
其中产生输出的等效Python代码
w =
[[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
v =
[[ 10. 10. 10. 10. 10.]
[ 20. 20. 20. 20. 20.]
[ 30. 30. 30. 30. 30.]
[ 40. 40. 40. 40. 40.]
[ 50. 50. 50. 50. 50.]]
idx =
[[0 2 2 0 3]
[1 2 1 2 4]
[2 2 4 3 4]
[0 1 1 4 4]
[0 1 0 4 3]]
w =
[[ 9. 0. 0. 0. 0.]
[ 19. 0. 0. 0. 0.]
[ 29. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]]
来源
2013-05-06 16:08:50
Jed
你说的话听起来正确。这可能会帮助你翻译:http://www.scipy.org/NumPy_for_Matlab_Users,但我会认为'w(idx(1:p,1),1)'变成'w [idx [:p,1] ,1]'python – Dan 2013-05-06 12:19:32
不要忘记基于零和基于一个索引 – Amro 2013-05-06 12:53:17