你对基本行为是正确的。索引矩阵第一列的一个p
长度子向量idx
被用于选择元素v
并将它们放在矩阵中的相同位置,w
然后首先通过标量调整它们的值theta
。
对 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
并且,等效的 Python 代码使用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
产生输出
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.]]