2
 mat = nan (5,4)

mat =

   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN
   NaN   NaN   NaN   NaN

fact = rand(5,4)

fact =

    0.3507    0.5870    0.8443    0.4357
    0.9390    0.2077    0.1948    0.3111
    0.8759    0.3012    0.2259    0.9234
    0.5502    0.4709    0.1707    0.4302
    0.6225    0.2305    0.2277    0.1848

cd =

     1
     5
     2
     3
     4

>> mat(cd, : ) = fact

mat =

    0.3507    0.5870    0.8443    0.4357
    0.8759    0.3012    0.2259    0.9234
    0.5502    0.4709    0.1707    0.4302
    0.6225    0.2305    0.2277    0.1848
    0.9390    0.2077    0.1948    0.3111

在 python 或 numpy 中是否有类似的东西可以完成最后一行的基本操作,即您可以输入一列索引,它会自动用相应的行填充 nan 矩阵,而不是遍历它并手动逐行执行此操作.

还注意到 cd 可以有比 mat 更多的行,并且 mat 可以自行相应地扩展,至少 matlab 可以。

4

2 回答 2

4

您可以在 python 中完全做到这一点,只需使用基于 0 的索引而不是基于 1 的索引:

>>> m[cd-1] = fact

>>> m 
array([[ 0.3507,  0.587 ,  0.8443,  0.4357],
       [ 0.8759,  0.3012,  0.2259,  0.9234],
       [ 0.5502,  0.4709,  0.1707,  0.4302],
       [ 0.6225,  0.2305,  0.2277,  0.1848],
       [ 0.939 ,  0.2077,  0.1948,  0.3111]])
于 2013-10-07T19:58:26.347 回答
3

我认为它的工作原理几乎相同:

>>> arr = np.empty((5,4))
>>> arr.fill(np.nan)
>>> arr
array([[ nan,  nan,  nan,  nan],
       [ nan,  nan,  nan,  nan],
       [ nan,  nan,  nan,  nan],
       [ nan,  nan,  nan,  nan],
       [ nan,  nan,  nan,  nan]])
>>> rand = np.random.random((5,4))
>>> rand
array([[ 0.10378825,  0.36936186,  0.65145694,  0.79532325],
       [ 0.69595542,  0.78740795,  0.31969862,  0.81173803],
       [ 0.06674611,  0.99920068,  0.78696773,  0.01768565],
       [ 0.9948402 ,  0.34200073,  0.60993921,  0.13801365],
       [ 0.18503791,  0.39392016,  0.64800295,  0.98816382]])
>>> cd = [0, 4, 1, 2, 3]   # Numpy arrays are 0-indexed.
>>> arr[cd, :] = rand
>>> arr
array([[ 0.10378825,  0.36936186,  0.65145694,  0.79532325],
       [ 0.06674611,  0.99920068,  0.78696773,  0.01768565],
       [ 0.9948402 ,  0.34200073,  0.60993921,  0.13801365],
       [ 0.18503791,  0.39392016,  0.64800295,  0.98816382],
       [ 0.69595542,  0.78740795,  0.31969862,  0.81173803]])
于 2013-10-07T19:58:17.460 回答