@@ -658,9 +658,8 @@ def __getitem__(self, item):
658
658
# The following functions complement those in twodim_base, but are
659
659
# applicable to N-dimensions.
660
660
661
- def fill_diagonal (a , val ):
662
- """
663
- Fill the main diagonal of the given array of any dimensionality.
661
+ def fill_diagonal (a , val , wrap = False ):
662
+ """Fill the main diagonal of the given array of any dimensionality.
664
663
665
664
For an array `a` with ``a.ndim > 2``, the diagonal is the list of
666
665
locations with indices ``a[i, i, ..., i]`` all identical. This function
@@ -675,6 +674,10 @@ def fill_diagonal(a, val):
675
674
Value to be written on the diagonal, its type must be compatible with
676
675
that of the array a.
677
676
677
+ wrap: bool For tall matrices in NumPy version up to 1.6.2, the
678
+ diagonal "wrapped" after N columns. You can have this behavior
679
+ with this option. This affect only tall matrices.
680
+
678
681
See also
679
682
--------
680
683
diag_indices, diag_indices_from
@@ -716,13 +719,42 @@ def fill_diagonal(a, val):
716
719
[0, 0, 0],
717
720
[0, 0, 4]])
718
721
722
+ # tall matrices no wrap
723
+ >>> a = np.zeros((5, 3),int)
724
+ >>> fill_diagonal(a, 4)
725
+ array([[4, 0, 0],
726
+ [0, 4, 0],
727
+ [0, 0, 4],
728
+ [0, 0, 0],
729
+ [0, 0, 0]])
730
+
731
+ # tall matrices wrap
732
+ >>> a = np.zeros((5, 3),int)
733
+ >>> fill_diagonal(a, 4)
734
+ array([[4, 0, 0],
735
+ [0, 4, 0],
736
+ [0, 0, 4],
737
+ [0, 0, 0],
738
+ [4, 0, 0]])
739
+
740
+ # wide matrices
741
+ >>> a = np.zeros((3, 5),int)
742
+ >>> fill_diagonal(a, 4)
743
+ array([[4, 0, 0, 0, 0],
744
+ [0, 4, 0, 0, 0],
745
+ [0, 0, 4, 0, 0]])
746
+
719
747
"""
720
748
if a .ndim < 2 :
721
749
raise ValueError ("array must be at least 2-d" )
750
+ end = None
722
751
if a .ndim == 2 :
723
752
# Explicit, fast formula for the common case. For 2-d arrays, we
724
753
# accept rectangular ones.
725
754
step = a .shape [1 ] + 1
755
+ #This is needed to don't have tall matrix have the diagonal wrap.
756
+ if not wrap :
757
+ end = a .shape [1 ] * a .shape [1 ]
726
758
else :
727
759
# For more than d=2, the strided formula is only valid for arrays with
728
760
# all dimensions equal, so we check first.
@@ -731,7 +763,7 @@ def fill_diagonal(a, val):
731
763
step = 1 + (cumprod (a .shape [:- 1 ])).sum ()
732
764
733
765
# Write the value out into the diagonal.
734
- a .flat [::step ] = val
766
+ a .flat [:end :step ] = val
735
767
736
768
737
769
def diag_indices (n , ndim = 2 ):
0 commit comments