你是對的基本行爲。來自索引矩陣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