nalgebra/base/
edition.rs

1use num::{One, Zero};
2use std::cmp;
3#[cfg(any(feature = "std", feature = "alloc"))]
4use std::iter::ExactSizeIterator;
5use std::ptr;
6
7use crate::base::allocator::{Allocator, Reallocator};
8use crate::base::constraint::{DimEq, SameNumberOfColumns, SameNumberOfRows, ShapeConstraint};
9#[cfg(any(feature = "std", feature = "alloc"))]
10use crate::base::dimension::Dyn;
11use crate::base::dimension::{Const, Dim, DimAdd, DimDiff, DimMin, DimMinimum, DimSub, DimSum, U1};
12use crate::base::storage::{RawStorage, RawStorageMut, ReshapableStorage};
13use crate::base::{DefaultAllocator, Matrix, OMatrix, RowVector, Scalar, Vector};
14use crate::{Storage, UninitMatrix};
15use std::mem::MaybeUninit;
16
17/// # Triangular matrix extraction
18impl<T: Scalar + Zero, R: Dim, C: Dim, S: Storage<T, R, C>> Matrix<T, R, C, S> {
19    /// Extracts the upper triangular part of this matrix (including the diagonal).
20    #[inline]
21    #[must_use]
22    pub fn upper_triangle(&self) -> OMatrix<T, R, C>
23    where
24        DefaultAllocator: Allocator<R, C>,
25    {
26        let mut res = self.clone_owned();
27        res.fill_lower_triangle(T::zero(), 1);
28
29        res
30    }
31
32    /// Extracts the lower triangular part of this matrix (including the diagonal).
33    #[inline]
34    #[must_use]
35    pub fn lower_triangle(&self) -> OMatrix<T, R, C>
36    where
37        DefaultAllocator: Allocator<R, C>,
38    {
39        let mut res = self.clone_owned();
40        res.fill_upper_triangle(T::zero(), 1);
41
42        res
43    }
44}
45
46/// # Rows and columns extraction
47impl<T: Scalar, R: Dim, C: Dim, S: Storage<T, R, C>> Matrix<T, R, C, S> {
48    /// Creates a new matrix by extracting the given set of rows from `self`.
49    #[cfg(any(feature = "std", feature = "alloc"))]
50    #[must_use]
51    pub fn select_rows<'a, I>(&self, irows: I) -> OMatrix<T, Dyn, C>
52    where
53        I: IntoIterator<Item = &'a usize>,
54        I::IntoIter: ExactSizeIterator + Clone,
55        DefaultAllocator: Allocator<Dyn, C>,
56    {
57        let irows = irows.into_iter();
58        let ncols = self.shape_generic().1;
59        let mut res = Matrix::uninit(Dyn(irows.len()), ncols);
60
61        // First, check that all the indices from irows are valid.
62        // This will allow us to use unchecked access in the inner loop.
63        for i in irows.clone() {
64            assert!(*i < self.nrows(), "Row index out of bounds.")
65        }
66
67        for j in 0..ncols.value() {
68            // TODO: use unchecked column indexing
69            let mut res = res.column_mut(j);
70            let src = self.column(j);
71
72            for (destination, source) in irows.clone().enumerate() {
73                // Safety: all indices are in range.
74                unsafe {
75                    *res.vget_unchecked_mut(destination) =
76                        MaybeUninit::new(src.vget_unchecked(*source).clone());
77                }
78            }
79        }
80
81        // Safety: res is now fully initialized.
82        unsafe { res.assume_init() }
83    }
84
85    /// Creates a new matrix by extracting the given set of columns from `self`.
86    #[cfg(any(feature = "std", feature = "alloc"))]
87    #[must_use]
88    pub fn select_columns<'a, I>(&self, icols: I) -> OMatrix<T, R, Dyn>
89    where
90        I: IntoIterator<Item = &'a usize>,
91        I::IntoIter: ExactSizeIterator,
92        DefaultAllocator: Allocator<R, Dyn>,
93    {
94        let icols = icols.into_iter();
95        let nrows = self.shape_generic().0;
96        let mut res = Matrix::uninit(nrows, Dyn(icols.len()));
97
98        for (destination, source) in icols.enumerate() {
99            // NOTE: this is basically a copy_frow but wrapping the values insnide of MaybeUninit.
100            res.column_mut(destination)
101                .zip_apply(&self.column(*source), |out, e| *out = MaybeUninit::new(e));
102        }
103
104        // Safety: res is now fully initialized.
105        unsafe { res.assume_init() }
106    }
107}
108
109/// # Set rows, columns, and diagonal
110impl<T: Scalar, R: Dim, C: Dim, S: RawStorageMut<T, R, C>> Matrix<T, R, C, S> {
111    /// Fills the diagonal of this matrix with the content of the given vector.
112    #[inline]
113    pub fn set_diagonal<R2: Dim, S2>(&mut self, diag: &Vector<T, R2, S2>)
114    where
115        R: DimMin<C>,
116        S2: RawStorage<T, R2>,
117        ShapeConstraint: DimEq<DimMinimum<R, C>, R2>,
118    {
119        let (nrows, ncols) = self.shape();
120        let min_nrows_ncols = cmp::min(nrows, ncols);
121        assert_eq!(diag.len(), min_nrows_ncols, "Mismatched dimensions.");
122
123        for i in 0..min_nrows_ncols {
124            unsafe { *self.get_unchecked_mut((i, i)) = diag.vget_unchecked(i).clone() }
125        }
126    }
127
128    /// Fills the diagonal of this matrix with the content of the given iterator.
129    ///
130    /// This will fill as many diagonal elements as the iterator yields, up to the
131    /// minimum of the number of rows and columns of `self`, and starting with the
132    /// diagonal element at index (0, 0).
133    #[inline]
134    pub fn set_partial_diagonal(&mut self, diag: impl Iterator<Item = T>) {
135        let (nrows, ncols) = self.shape();
136        let min_nrows_ncols = cmp::min(nrows, ncols);
137
138        for (i, val) in diag.enumerate().take(min_nrows_ncols) {
139            unsafe { *self.get_unchecked_mut((i, i)) = val }
140        }
141    }
142
143    /// Fills the selected row of this matrix with the content of the given vector.
144    #[inline]
145    pub fn set_row<C2: Dim, S2>(&mut self, i: usize, row: &RowVector<T, C2, S2>)
146    where
147        S2: RawStorage<T, U1, C2>,
148        ShapeConstraint: SameNumberOfColumns<C, C2>,
149    {
150        self.row_mut(i).copy_from(row);
151    }
152
153    /// Fills the selected column of this matrix with the content of the given vector.
154    #[inline]
155    pub fn set_column<R2: Dim, S2>(&mut self, i: usize, column: &Vector<T, R2, S2>)
156    where
157        S2: RawStorage<T, R2, U1>,
158        ShapeConstraint: SameNumberOfRows<R, R2>,
159    {
160        self.column_mut(i).copy_from(column);
161    }
162}
163
164/// # In-place filling
165impl<T, R: Dim, C: Dim, S: RawStorageMut<T, R, C>> Matrix<T, R, C, S> {
166    /// Sets all the elements of this matrix to the value returned by the closure.
167    #[inline]
168    pub fn fill_with(&mut self, val: impl Fn() -> T) {
169        for e in self.iter_mut() {
170            *e = val()
171        }
172    }
173
174    /// Sets all the elements of this matrix to `val`.
175    #[inline]
176    pub fn fill(&mut self, val: T)
177    where
178        T: Scalar,
179    {
180        for e in self.iter_mut() {
181            *e = val.clone()
182        }
183    }
184
185    /// Fills `self` with the identity matrix.
186    #[inline]
187    pub fn fill_with_identity(&mut self)
188    where
189        T: Scalar + Zero + One,
190    {
191        self.fill(T::zero());
192        self.fill_diagonal(T::one());
193    }
194
195    /// Sets all the diagonal elements of this matrix to `val`.
196    #[inline]
197    pub fn fill_diagonal(&mut self, val: T)
198    where
199        T: Scalar,
200    {
201        let (nrows, ncols) = self.shape();
202        let n = cmp::min(nrows, ncols);
203
204        for i in 0..n {
205            unsafe { *self.get_unchecked_mut((i, i)) = val.clone() }
206        }
207    }
208
209    /// Sets all the elements of the selected row to `val`.
210    #[inline]
211    pub fn fill_row(&mut self, i: usize, val: T)
212    where
213        T: Scalar,
214    {
215        assert!(i < self.nrows(), "Row index out of bounds.");
216        for j in 0..self.ncols() {
217            unsafe { *self.get_unchecked_mut((i, j)) = val.clone() }
218        }
219    }
220
221    /// Sets all the elements of the selected column to `val`.
222    #[inline]
223    pub fn fill_column(&mut self, j: usize, val: T)
224    where
225        T: Scalar,
226    {
227        assert!(j < self.ncols(), "Row index out of bounds.");
228        for i in 0..self.nrows() {
229            unsafe { *self.get_unchecked_mut((i, j)) = val.clone() }
230        }
231    }
232
233    /// Sets all the elements of the lower-triangular part of this matrix to `val`.
234    ///
235    /// The parameter `shift` allows some subdiagonals to be left untouched:
236    /// * If `shift = 0` then the diagonal is overwritten as well.
237    /// * If `shift = 1` then the diagonal is left untouched.
238    /// * If `shift > 1`, then the diagonal and the first `shift - 1` subdiagonals are left
239    ///   untouched.
240    #[inline]
241    pub fn fill_lower_triangle(&mut self, val: T, shift: usize)
242    where
243        T: Scalar,
244    {
245        for j in 0..self.ncols() {
246            for i in (j + shift)..self.nrows() {
247                unsafe { *self.get_unchecked_mut((i, j)) = val.clone() }
248            }
249        }
250    }
251
252    /// Sets all the elements of the lower-triangular part of this matrix to `val`.
253    ///
254    /// The parameter `shift` allows some superdiagonals to be left untouched:
255    /// * If `shift = 0` then the diagonal is overwritten as well.
256    /// * If `shift = 1` then the diagonal is left untouched.
257    /// * If `shift > 1`, then the diagonal and the first `shift - 1` superdiagonals are left
258    ///   untouched.
259    #[inline]
260    pub fn fill_upper_triangle(&mut self, val: T, shift: usize)
261    where
262        T: Scalar,
263    {
264        for j in shift..self.ncols() {
265            // TODO: is there a more efficient way to avoid the min ?
266            // (necessary for rectangular matrices)
267            for i in 0..cmp::min(j + 1 - shift, self.nrows()) {
268                unsafe { *self.get_unchecked_mut((i, j)) = val.clone() }
269            }
270        }
271    }
272}
273
274impl<T: Scalar, D: Dim, S: RawStorageMut<T, D, D>> Matrix<T, D, D, S> {
275    /// Copies the upper-triangle of this matrix to its lower-triangular part.
276    ///
277    /// This makes the matrix symmetric. Panics if the matrix is not square.
278    pub fn fill_lower_triangle_with_upper_triangle(&mut self) {
279        assert!(self.is_square(), "The input matrix should be square.");
280
281        let dim = self.nrows();
282        for j in 0..dim {
283            for i in j + 1..dim {
284                unsafe {
285                    *self.get_unchecked_mut((i, j)) = self.get_unchecked((j, i)).clone();
286                }
287            }
288        }
289    }
290
291    /// Copies the upper-triangle of this matrix to its upper-triangular part.
292    ///
293    /// This makes the matrix symmetric. Panics if the matrix is not square.
294    pub fn fill_upper_triangle_with_lower_triangle(&mut self) {
295        assert!(self.is_square(), "The input matrix should be square.");
296
297        for j in 1..self.ncols() {
298            for i in 0..j {
299                unsafe {
300                    *self.get_unchecked_mut((i, j)) = self.get_unchecked((j, i)).clone();
301                }
302            }
303        }
304    }
305}
306
307/// # In-place swapping
308impl<T: Scalar, R: Dim, C: Dim, S: RawStorageMut<T, R, C>> Matrix<T, R, C, S> {
309    /// Swaps two rows in-place.
310    #[inline]
311    pub fn swap_rows(&mut self, irow1: usize, irow2: usize) {
312        assert!(irow1 < self.nrows() && irow2 < self.nrows());
313
314        if irow1 != irow2 {
315            // TODO: optimize that.
316            for i in 0..self.ncols() {
317                unsafe { self.swap_unchecked((irow1, i), (irow2, i)) }
318            }
319        }
320        // Otherwise do nothing.
321    }
322
323    /// Swaps two columns in-place.
324    #[inline]
325    pub fn swap_columns(&mut self, icol1: usize, icol2: usize) {
326        assert!(icol1 < self.ncols() && icol2 < self.ncols());
327
328        if icol1 != icol2 {
329            // TODO: optimize that.
330            for i in 0..self.nrows() {
331                unsafe { self.swap_unchecked((i, icol1), (i, icol2)) }
332            }
333        }
334        // Otherwise do nothing.
335    }
336}
337
338/*
339 *
340 * TODO: specialize all the following for slices.
341 *
342 */
343/// # Rows and columns removal
344impl<T: Scalar, R: Dim, C: Dim, S: Storage<T, R, C>> Matrix<T, R, C, S> {
345    /*
346     *
347     * Column removal.
348     *
349     */
350    /// Removes the `i`-th column from this matrix.
351    #[inline]
352    pub fn remove_column(self, i: usize) -> OMatrix<T, R, DimDiff<C, U1>>
353    where
354        C: DimSub<U1>,
355        DefaultAllocator: Reallocator<T, R, C, R, DimDiff<C, U1>>,
356    {
357        self.remove_fixed_columns::<1>(i)
358    }
359
360    /// Removes all columns in `indices`   
361    #[cfg(any(feature = "std", feature = "alloc"))]
362    pub fn remove_columns_at(self, indices: &[usize]) -> OMatrix<T, R, Dyn>
363    where
364        C: DimSub<Dyn, Output = Dyn>,
365        DefaultAllocator: Reallocator<T, R, C, R, Dyn>,
366    {
367        let mut m = self.into_owned();
368        let (nrows, ncols) = m.shape_generic();
369        let mut offset: usize = 0;
370        let mut target: usize = 0;
371        while offset + target < ncols.value() {
372            if indices.contains(&(target + offset)) {
373                // Safety: the resulting pointer is within range.
374                let col_ptr = unsafe { m.data.ptr_mut().add((target + offset) * nrows.value()) };
375                // Drop every element in the column we are about to overwrite.
376                // We use the a similar technique as in `Vec::truncate`.
377                let s = ptr::slice_from_raw_parts_mut(col_ptr, nrows.value());
378                // Safety: we drop the column in-place, which is OK because we will overwrite these
379                //         entries later in the loop, or discard them with the `reallocate_copy`
380                //         afterwards.
381                unsafe { ptr::drop_in_place(s) };
382
383                offset += 1;
384            } else {
385                unsafe {
386                    let ptr_source = m.data.ptr().add((target + offset) * nrows.value());
387                    let ptr_target = m.data.ptr_mut().add(target * nrows.value());
388
389                    // Copy the data, overwriting what we dropped.
390                    ptr::copy(ptr_source, ptr_target, nrows.value());
391                    target += 1;
392                }
393            }
394        }
395
396        // Safety: The new size is smaller than the old size, so
397        //         DefaultAllocator::reallocate_copy will initialize
398        //         every element of the new matrix which can then
399        //         be assumed to be initialized.
400        unsafe {
401            let new_data = DefaultAllocator::reallocate_copy(
402                nrows,
403                ncols.sub(Dyn::from_usize(offset)),
404                m.data,
405            );
406
407            Matrix::from_data(new_data).assume_init()
408        }
409    }
410
411    /// Removes all rows in `indices`   
412    #[cfg(any(feature = "std", feature = "alloc"))]
413    pub fn remove_rows_at(self, indices: &[usize]) -> OMatrix<T, Dyn, C>
414    where
415        R: DimSub<Dyn, Output = Dyn>,
416        DefaultAllocator: Reallocator<T, R, C, Dyn, C>,
417    {
418        let mut m = self.into_owned();
419        let (nrows, ncols) = m.shape_generic();
420        let mut offset: usize = 0;
421        let mut target: usize = 0;
422        while offset + target < nrows.value() * ncols.value() {
423            if indices.contains(&((target + offset) % nrows.value())) {
424                // Safety: the resulting pointer is within range.
425                unsafe {
426                    let elt_ptr = m.data.ptr_mut().add(target + offset);
427                    // Safety: we drop the component in-place, which is OK because we will overwrite these
428                    //         entries later in the loop, or discard them with the `reallocate_copy`
429                    //         afterwards.
430                    ptr::drop_in_place(elt_ptr)
431                };
432                offset += 1;
433            } else {
434                unsafe {
435                    let ptr_source = m.data.ptr().add(target + offset);
436                    let ptr_target = m.data.ptr_mut().add(target);
437
438                    // Copy the data, overwriting what we dropped in the previous iterations.
439                    ptr::copy(ptr_source, ptr_target, 1);
440                    target += 1;
441                }
442            }
443        }
444
445        // Safety: The new size is smaller than the old size, so
446        //         DefaultAllocator::reallocate_copy will initialize
447        //         every element of the new matrix which can then
448        //         be assumed to be initialized.
449        unsafe {
450            let new_data = DefaultAllocator::reallocate_copy(
451                nrows.sub(Dyn::from_usize(offset / ncols.value())),
452                ncols,
453                m.data,
454            );
455
456            Matrix::from_data(new_data).assume_init()
457        }
458    }
459
460    /// Removes `D::dim()` consecutive columns from this matrix, starting with the `i`-th
461    /// (included).
462    #[inline]
463    pub fn remove_fixed_columns<const D: usize>(
464        self,
465        i: usize,
466    ) -> OMatrix<T, R, DimDiff<C, Const<D>>>
467    where
468        C: DimSub<Const<D>>,
469        DefaultAllocator: Reallocator<T, R, C, R, DimDiff<C, Const<D>>>,
470    {
471        self.remove_columns_generic(i, Const::<D>)
472    }
473
474    /// Removes `n` consecutive columns from this matrix, starting with the `i`-th (included).
475    #[inline]
476    #[cfg(any(feature = "std", feature = "alloc"))]
477    pub fn remove_columns(self, i: usize, n: usize) -> OMatrix<T, R, Dyn>
478    where
479        C: DimSub<Dyn, Output = Dyn>,
480        DefaultAllocator: Reallocator<T, R, C, R, Dyn>,
481    {
482        self.remove_columns_generic(i, Dyn(n))
483    }
484
485    /// Removes `nremove.value()` columns from this matrix, starting with the `i`-th (included).
486    ///
487    /// This is the generic implementation of `.remove_columns(...)` and
488    /// `.remove_fixed_columns(...)` which have nicer API interfaces.
489    #[inline]
490    pub fn remove_columns_generic<D>(self, i: usize, nremove: D) -> OMatrix<T, R, DimDiff<C, D>>
491    where
492        D: Dim,
493        C: DimSub<D>,
494        DefaultAllocator: Reallocator<T, R, C, R, DimDiff<C, D>>,
495    {
496        let mut m = self.into_owned();
497        let (nrows, ncols) = m.shape_generic();
498        assert!(
499            i + nremove.value() <= ncols.value(),
500            "Column index out of range."
501        );
502
503        let need_column_shifts = nremove.value() != 0 && i + nremove.value() < ncols.value();
504        if need_column_shifts {
505            // The first `deleted_i * nrows` are left untouched.
506            let copied_value_start = i + nremove.value();
507
508            unsafe {
509                let ptr_in = m.data.ptr().add(copied_value_start * nrows.value());
510                let ptr_out = m.data.ptr_mut().add(i * nrows.value());
511
512                // Drop all the elements of the columns we are about to overwrite.
513                // We use the a similar technique as in `Vec::truncate`.
514                let s = ptr::slice_from_raw_parts_mut(ptr_out, nremove.value() * nrows.value());
515                // Safety: we drop the column in-place, which is OK because we will overwrite these
516                //         entries with `ptr::copy` afterward.
517                ptr::drop_in_place(s);
518
519                ptr::copy(
520                    ptr_in,
521                    ptr_out,
522                    (ncols.value() - copied_value_start) * nrows.value(),
523                );
524            }
525        } else {
526            // All the columns to remove are at the end of the buffer. Drop them.
527            unsafe {
528                let ptr = m.data.ptr_mut().add(i * nrows.value());
529                let s = ptr::slice_from_raw_parts_mut(ptr, nremove.value() * nrows.value());
530                ptr::drop_in_place(s)
531            };
532        }
533
534        // Safety: The new size is smaller than the old size, so
535        //         DefaultAllocator::reallocate_copy will initialize
536        //         every element of the new matrix which can then
537        //         be assumed to be initialized.
538        unsafe {
539            let new_data = DefaultAllocator::reallocate_copy(nrows, ncols.sub(nremove), m.data);
540            Matrix::from_data(new_data).assume_init()
541        }
542    }
543
544    /*
545     *
546     * Row removal.
547     *
548     */
549    /// Removes the `i`-th row from this matrix.
550    #[inline]
551    pub fn remove_row(self, i: usize) -> OMatrix<T, DimDiff<R, U1>, C>
552    where
553        R: DimSub<U1>,
554        DefaultAllocator: Reallocator<T, R, C, DimDiff<R, U1>, C>,
555    {
556        self.remove_fixed_rows::<1>(i)
557    }
558
559    /// Removes `D::dim()` consecutive rows from this matrix, starting with the `i`-th (included).
560    #[inline]
561    pub fn remove_fixed_rows<const D: usize>(self, i: usize) -> OMatrix<T, DimDiff<R, Const<D>>, C>
562    where
563        R: DimSub<Const<D>>,
564        DefaultAllocator: Reallocator<T, R, C, DimDiff<R, Const<D>>, C>,
565    {
566        self.remove_rows_generic(i, Const::<D>)
567    }
568
569    /// Removes `n` consecutive rows from this matrix, starting with the `i`-th (included).
570    #[inline]
571    #[cfg(any(feature = "std", feature = "alloc"))]
572    pub fn remove_rows(self, i: usize, n: usize) -> OMatrix<T, Dyn, C>
573    where
574        R: DimSub<Dyn, Output = Dyn>,
575        DefaultAllocator: Reallocator<T, R, C, Dyn, C>,
576    {
577        self.remove_rows_generic(i, Dyn(n))
578    }
579
580    /// Removes `nremove.value()` rows from this matrix, starting with the `i`-th (included).
581    ///
582    /// This is the generic implementation of `.remove_rows(...)` and `.remove_fixed_rows(...)`
583    /// which have nicer API interfaces.
584    #[inline]
585    pub fn remove_rows_generic<D>(self, i: usize, nremove: D) -> OMatrix<T, DimDiff<R, D>, C>
586    where
587        D: Dim,
588        R: DimSub<D>,
589        DefaultAllocator: Reallocator<T, R, C, DimDiff<R, D>, C>,
590    {
591        let mut m = self.into_owned();
592        let (nrows, ncols) = m.shape_generic();
593        assert!(
594            i + nremove.value() <= nrows.value(),
595            "Row index out of range."
596        );
597
598        if nremove.value() != 0 {
599            unsafe {
600                compress_rows(
601                    m.as_mut_slice(),
602                    nrows.value(),
603                    ncols.value(),
604                    i,
605                    nremove.value(),
606                );
607            }
608        }
609
610        // Safety: The new size is smaller than the old size, so
611        //         DefaultAllocator::reallocate_copy will initialize
612        //         every element of the new matrix which can then
613        //         be assumed to be initialized.
614        unsafe {
615            let new_data = DefaultAllocator::reallocate_copy(nrows.sub(nremove), ncols, m.data);
616            Matrix::from_data(new_data).assume_init()
617        }
618    }
619}
620
621/// # Rows and columns insertion
622impl<T: Scalar, R: Dim, C: Dim, S: Storage<T, R, C>> Matrix<T, R, C, S> {
623    /*
624     *
625     * Columns insertion.
626     *
627     */
628    /// Inserts a column filled with `val` at the `i-th` position.
629    #[inline]
630    pub fn insert_column(self, i: usize, val: T) -> OMatrix<T, R, DimSum<C, U1>>
631    where
632        C: DimAdd<U1>,
633        DefaultAllocator: Reallocator<T, R, C, R, DimSum<C, U1>>,
634    {
635        self.insert_fixed_columns::<1>(i, val)
636    }
637
638    /// Inserts `D` columns filled with `val` starting at the `i-th` position.
639    #[inline]
640    pub fn insert_fixed_columns<const D: usize>(
641        self,
642        i: usize,
643        val: T,
644    ) -> OMatrix<T, R, DimSum<C, Const<D>>>
645    where
646        C: DimAdd<Const<D>>,
647        DefaultAllocator: Reallocator<T, R, C, R, DimSum<C, Const<D>>>,
648    {
649        let mut res = unsafe { self.insert_columns_generic_uninitialized(i, Const::<D>) };
650        res.fixed_columns_mut::<D>(i)
651            .fill_with(|| MaybeUninit::new(val.clone()));
652
653        // Safety: the result is now fully initialized. The added columns have
654        //         been initialized by the `fill_with` above, and the rest have
655        //         been initialized by `insert_columns_generic_uninitialized`.
656        unsafe { res.assume_init() }
657    }
658
659    /// Inserts `n` columns filled with `val` starting at the `i-th` position.
660    #[inline]
661    #[cfg(any(feature = "std", feature = "alloc"))]
662    pub fn insert_columns(self, i: usize, n: usize, val: T) -> OMatrix<T, R, Dyn>
663    where
664        C: DimAdd<Dyn, Output = Dyn>,
665        DefaultAllocator: Reallocator<T, R, C, R, Dyn>,
666    {
667        let mut res = unsafe { self.insert_columns_generic_uninitialized(i, Dyn(n)) };
668        res.columns_mut(i, n)
669            .fill_with(|| MaybeUninit::new(val.clone()));
670
671        // Safety: the result is now fully initialized. The added columns have
672        //         been initialized by the `fill_with` above, and the rest have
673        //         been initialized by `insert_columns_generic_uninitialized`.
674        unsafe { res.assume_init() }
675    }
676
677    /// Inserts `ninsert.value()` columns starting at the `i-th` place of this matrix.
678    ///
679    /// # Safety
680    /// The output matrix has all its elements initialized except for the the components of the
681    /// added columns.
682    #[inline]
683    pub unsafe fn insert_columns_generic_uninitialized<D>(
684        self,
685        i: usize,
686        ninsert: D,
687    ) -> UninitMatrix<T, R, DimSum<C, D>>
688    where
689        D: Dim,
690        C: DimAdd<D>,
691        DefaultAllocator: Reallocator<T, R, C, R, DimSum<C, D>>,
692    {
693        let m = self.into_owned();
694        let (nrows, ncols) = m.shape_generic();
695        let mut res = Matrix::from_data(DefaultAllocator::reallocate_copy(
696            nrows,
697            ncols.add(ninsert),
698            m.data,
699        ));
700
701        assert!(i <= ncols.value(), "Column insertion index out of range.");
702
703        if ninsert.value() != 0 && i != ncols.value() {
704            let ptr_in = res.data.ptr().add(i * nrows.value());
705            let ptr_out = res
706                .data
707                .ptr_mut()
708                .add((i + ninsert.value()) * nrows.value());
709
710            ptr::copy(ptr_in, ptr_out, (ncols.value() - i) * nrows.value())
711        }
712
713        res
714    }
715
716    /*
717     *
718     * Rows insertion.
719     *
720     */
721    /// Inserts a row filled with `val` at the `i-th` position.
722    #[inline]
723    pub fn insert_row(self, i: usize, val: T) -> OMatrix<T, DimSum<R, U1>, C>
724    where
725        R: DimAdd<U1>,
726        DefaultAllocator: Reallocator<T, R, C, DimSum<R, U1>, C>,
727    {
728        self.insert_fixed_rows::<1>(i, val)
729    }
730
731    /// Inserts `D::dim()` rows filled with `val` starting at the `i-th` position.
732    #[inline]
733    pub fn insert_fixed_rows<const D: usize>(
734        self,
735        i: usize,
736        val: T,
737    ) -> OMatrix<T, DimSum<R, Const<D>>, C>
738    where
739        R: DimAdd<Const<D>>,
740        DefaultAllocator: Reallocator<T, R, C, DimSum<R, Const<D>>, C>,
741    {
742        let mut res = unsafe { self.insert_rows_generic_uninitialized(i, Const::<D>) };
743        res.fixed_rows_mut::<D>(i)
744            .fill_with(|| MaybeUninit::new(val.clone()));
745
746        // Safety: the result is now fully initialized. The added rows have
747        //         been initialized by the `fill_with` above, and the rest have
748        //         been initialized by `insert_rows_generic_uninitialized`.
749        unsafe { res.assume_init() }
750    }
751
752    /// Inserts `n` rows filled with `val` starting at the `i-th` position.
753    #[inline]
754    #[cfg(any(feature = "std", feature = "alloc"))]
755    pub fn insert_rows(self, i: usize, n: usize, val: T) -> OMatrix<T, Dyn, C>
756    where
757        R: DimAdd<Dyn, Output = Dyn>,
758        DefaultAllocator: Reallocator<T, R, C, Dyn, C>,
759    {
760        let mut res = unsafe { self.insert_rows_generic_uninitialized(i, Dyn(n)) };
761        res.rows_mut(i, n)
762            .fill_with(|| MaybeUninit::new(val.clone()));
763
764        // Safety: the result is now fully initialized. The added rows have
765        //         been initialized by the `fill_with` above, and the rest have
766        //         been initialized by `insert_rows_generic_uninitialized`.
767        unsafe { res.assume_init() }
768    }
769
770    /// Inserts `ninsert.value()` rows at the `i-th` place of this matrix.
771    ///
772    /// # Safety
773    /// The added rows values are not initialized.
774    /// This is the generic implementation of `.insert_rows(...)` and
775    /// `.insert_fixed_rows(...)` which have nicer API interfaces.
776    #[inline]
777    pub unsafe fn insert_rows_generic_uninitialized<D>(
778        self,
779        i: usize,
780        ninsert: D,
781    ) -> UninitMatrix<T, DimSum<R, D>, C>
782    where
783        D: Dim,
784        R: DimAdd<D>,
785        DefaultAllocator: Reallocator<T, R, C, DimSum<R, D>, C>,
786    {
787        let m = self.into_owned();
788        let (nrows, ncols) = m.shape_generic();
789        let mut res = Matrix::from_data(DefaultAllocator::reallocate_copy(
790            nrows.add(ninsert),
791            ncols,
792            m.data,
793        ));
794
795        assert!(i <= nrows.value(), "Row insertion index out of range.");
796
797        if ninsert.value() != 0 {
798            extend_rows(
799                res.as_mut_slice(),
800                nrows.value(),
801                ncols.value(),
802                i,
803                ninsert.value(),
804            );
805        }
806
807        res
808    }
809}
810
811/// # Resizing and reshaping
812impl<T: Scalar, R: Dim, C: Dim, S: Storage<T, R, C>> Matrix<T, R, C, S> {
813    /// Resizes this matrix so that it contains `new_nrows` rows and `new_ncols` columns.
814    ///
815    /// The values are copied such that `self[(i, j)] == result[(i, j)]`. If the result has more
816    /// rows and/or columns than `self`, then the extra rows or columns are filled with `val`.
817    #[cfg(any(feature = "std", feature = "alloc"))]
818    pub fn resize(self, new_nrows: usize, new_ncols: usize, val: T) -> OMatrix<T, Dyn, Dyn>
819    where
820        DefaultAllocator: Reallocator<T, R, C, Dyn, Dyn>,
821    {
822        self.resize_generic(Dyn(new_nrows), Dyn(new_ncols), val)
823    }
824
825    /// Resizes this matrix vertically, i.e., so that it contains `new_nrows` rows while keeping the same number of columns.
826    ///
827    /// The values are copied such that `self[(i, j)] == result[(i, j)]`. If the result has more
828    /// rows than `self`, then the extra rows are filled with `val`.
829    #[cfg(any(feature = "std", feature = "alloc"))]
830    pub fn resize_vertically(self, new_nrows: usize, val: T) -> OMatrix<T, Dyn, C>
831    where
832        DefaultAllocator: Reallocator<T, R, C, Dyn, C>,
833    {
834        let ncols = self.shape_generic().1;
835        self.resize_generic(Dyn(new_nrows), ncols, val)
836    }
837
838    /// Resizes this matrix horizontally, i.e., so that it contains `new_ncolumns` columns while keeping the same number of columns.
839    ///
840    /// The values are copied such that `self[(i, j)] == result[(i, j)]`. If the result has more
841    /// columns than `self`, then the extra columns are filled with `val`.
842    #[cfg(any(feature = "std", feature = "alloc"))]
843    pub fn resize_horizontally(self, new_ncols: usize, val: T) -> OMatrix<T, R, Dyn>
844    where
845        DefaultAllocator: Reallocator<T, R, C, R, Dyn>,
846    {
847        let nrows = self.shape_generic().0;
848        self.resize_generic(nrows, Dyn(new_ncols), val)
849    }
850
851    /// Resizes this matrix so that it contains `R2::value()` rows and `C2::value()` columns.
852    ///
853    /// The values are copied such that `self[(i, j)] == result[(i, j)]`. If the result has more
854    /// rows and/or columns than `self`, then the extra rows or columns are filled with `val`.
855    pub fn fixed_resize<const R2: usize, const C2: usize>(
856        self,
857        val: T,
858    ) -> OMatrix<T, Const<R2>, Const<C2>>
859    where
860        DefaultAllocator: Reallocator<T, R, C, Const<R2>, Const<C2>>,
861    {
862        self.resize_generic(Const::<R2>, Const::<C2>, val)
863    }
864
865    /// Resizes `self` such that it has dimensions `new_nrows × new_ncols`.
866    ///
867    /// The values are copied such that `self[(i, j)] == result[(i, j)]`. If the result has more
868    /// rows and/or columns than `self`, then the extra rows or columns are filled with `val`.
869    #[inline]
870    pub fn resize_generic<R2: Dim, C2: Dim>(
871        self,
872        new_nrows: R2,
873        new_ncols: C2,
874        val: T,
875    ) -> OMatrix<T, R2, C2>
876    where
877        DefaultAllocator: Reallocator<T, R, C, R2, C2>,
878    {
879        let (nrows, ncols) = self.shape();
880        let mut data = self.into_owned();
881
882        if new_nrows.value() == nrows {
883            if new_ncols.value() < ncols {
884                unsafe {
885                    let num_cols_to_delete = ncols - new_ncols.value();
886                    let col_ptr = data.data.ptr_mut().add(new_ncols.value() * nrows);
887                    let s = ptr::slice_from_raw_parts_mut(col_ptr, num_cols_to_delete * nrows);
888                    // Safety: drop the elements of the deleted columns.
889                    //         these are the elements that will be truncated
890                    //         by the `reallocate_copy` afterward.
891                    ptr::drop_in_place(s)
892                };
893            }
894
895            let res = unsafe { DefaultAllocator::reallocate_copy(new_nrows, new_ncols, data.data) };
896            let mut res = Matrix::from_data(res);
897
898            if new_ncols.value() > ncols {
899                res.columns_range_mut(ncols..)
900                    .fill_with(|| MaybeUninit::new(val.clone()));
901            }
902
903            // Safety: the result is now fully initialized by `reallocate_copy` and
904            //         `fill_with` (if the output has more columns than the input).
905            unsafe { res.assume_init() }
906        } else {
907            let mut res;
908
909            unsafe {
910                if new_nrows.value() < nrows {
911                    compress_rows(
912                        data.as_mut_slice(),
913                        nrows,
914                        ncols,
915                        new_nrows.value(),
916                        nrows - new_nrows.value(),
917                    );
918                    res = Matrix::from_data(DefaultAllocator::reallocate_copy(
919                        new_nrows, new_ncols, data.data,
920                    ));
921                } else {
922                    res = Matrix::from_data(DefaultAllocator::reallocate_copy(
923                        new_nrows, new_ncols, data.data,
924                    ));
925                    extend_rows(
926                        res.as_mut_slice(),
927                        nrows,
928                        new_ncols.value(),
929                        nrows,
930                        new_nrows.value() - nrows,
931                    );
932                }
933            }
934
935            if new_ncols.value() > ncols {
936                res.columns_range_mut(ncols..)
937                    .fill_with(|| MaybeUninit::new(val.clone()));
938            }
939
940            if new_nrows.value() > nrows {
941                res.view_range_mut(nrows.., ..cmp::min(ncols, new_ncols.value()))
942                    .fill_with(|| MaybeUninit::new(val.clone()));
943            }
944
945            // Safety: the result is now fully initialized by `reallocate_copy` and
946            //         `fill_with` (whenever applicable).
947            unsafe { res.assume_init() }
948        }
949    }
950
951    /// Reshapes `self` such that it has dimensions `new_nrows × new_ncols`.
952    ///
953    /// This will reinterpret `self` as if it is a matrix with `new_nrows` rows and `new_ncols`
954    /// columns. The arrangements of the component in the output matrix are the same as what
955    /// would be obtained by `Matrix::from_slice_generic(self.as_slice(), new_nrows, new_ncols)`.
956    ///
957    /// If `self` is a dynamically-sized matrix, then its components are neither copied nor moved.
958    /// If `self` is staticyll-sized, then a copy may happen in some situations.
959    /// This function will panic if the given dimensions are such that the number of elements of
960    /// the input matrix are not equal to the number of elements of the output matrix.
961    ///
962    /// # Examples
963    ///
964    /// ```
965    /// # use nalgebra::{Matrix3x2, Matrix2x3, DMatrix, Const, Dyn};
966    ///
967    /// let m1 = Matrix2x3::new(
968    ///     1.1, 1.2, 1.3,
969    ///     2.1, 2.2, 2.3
970    /// );
971    /// let m2 = Matrix3x2::new(
972    ///     1.1, 2.2,
973    ///     2.1, 1.3,
974    ///     1.2, 2.3
975    /// );
976    /// let reshaped = m1.reshape_generic(Const::<3>, Const::<2>);
977    /// assert_eq!(reshaped, m2);
978    ///
979    /// let dm1 = DMatrix::from_row_slice(
980    ///     4,
981    ///     3,
982    ///     &[
983    ///         1.0, 0.0, 0.0,
984    ///         0.0, 0.0, 1.0,
985    ///         0.0, 0.0, 0.0,
986    ///         0.0, 1.0, 0.0
987    ///     ],
988    /// );
989    /// let dm2 = DMatrix::from_row_slice(
990    ///     6,
991    ///     2,
992    ///     &[
993    ///         1.0, 0.0,
994    ///         0.0, 1.0,
995    ///         0.0, 0.0,
996    ///         0.0, 1.0,
997    ///         0.0, 0.0,
998    ///         0.0, 0.0,
999    ///     ],
1000    /// );
1001    /// let reshaped = dm1.reshape_generic(Dyn(6), Dyn(2));
1002    /// assert_eq!(reshaped, dm2);
1003    /// ```
1004    pub fn reshape_generic<R2, C2>(
1005        self,
1006        new_nrows: R2,
1007        new_ncols: C2,
1008    ) -> Matrix<T, R2, C2, S::Output>
1009    where
1010        R2: Dim,
1011        C2: Dim,
1012        S: ReshapableStorage<T, R, C, R2, C2>,
1013    {
1014        let data = self.data.reshape_generic(new_nrows, new_ncols);
1015        Matrix::from_data(data)
1016    }
1017}
1018
1019/// # In-place resizing
1020#[cfg(any(feature = "std", feature = "alloc"))]
1021impl<T: Scalar> OMatrix<T, Dyn, Dyn> {
1022    /// Resizes this matrix in-place.
1023    ///
1024    /// The values are copied such that `self[(i, j)] == result[(i, j)]`. If the result has more
1025    /// rows and/or columns than `self`, then the extra rows or columns are filled with `val`.
1026    ///
1027    /// Defined only for owned fully-dynamic matrices, i.e., `DMatrix`.
1028    pub fn resize_mut(&mut self, new_nrows: usize, new_ncols: usize, val: T)
1029    where
1030        DefaultAllocator: Reallocator<T, Dyn, Dyn, Dyn, Dyn>,
1031    {
1032        // TODO: avoid the clone.
1033        *self = self.clone().resize(new_nrows, new_ncols, val);
1034    }
1035}
1036
1037#[cfg(any(feature = "std", feature = "alloc"))]
1038impl<T: Scalar, C: Dim> OMatrix<T, Dyn, C>
1039where
1040    DefaultAllocator: Allocator<Dyn, C>,
1041{
1042    /// Changes the number of rows of this matrix in-place.
1043    ///
1044    /// The values are copied such that `self[(i, j)] == result[(i, j)]`. If the result has more
1045    /// rows than `self`, then the extra rows are filled with `val`.
1046    ///
1047    /// Defined only for owned matrices with a dynamic number of rows (for example, `DVector`).
1048    #[cfg(any(feature = "std", feature = "alloc"))]
1049    pub fn resize_vertically_mut(&mut self, new_nrows: usize, val: T)
1050    where
1051        DefaultAllocator: Reallocator<T, Dyn, C, Dyn, C>,
1052    {
1053        // TODO: avoid the clone.
1054        *self = self.clone().resize_vertically(new_nrows, val);
1055    }
1056}
1057
1058#[cfg(any(feature = "std", feature = "alloc"))]
1059impl<T: Scalar, R: Dim> OMatrix<T, R, Dyn>
1060where
1061    DefaultAllocator: Allocator<R, Dyn>,
1062{
1063    /// Changes the number of column of this matrix in-place.
1064    ///
1065    /// The values are copied such that `self[(i, j)] == result[(i, j)]`. If the result has more
1066    /// columns than `self`, then the extra columns are filled with `val`.
1067    ///
1068    /// Defined only for owned matrices with a dynamic number of columns (for example, `DVector`).
1069    #[cfg(any(feature = "std", feature = "alloc"))]
1070    pub fn resize_horizontally_mut(&mut self, new_ncols: usize, val: T)
1071    where
1072        DefaultAllocator: Reallocator<T, R, Dyn, R, Dyn>,
1073    {
1074        // TODO: avoid the clone.
1075        *self = self.clone().resize_horizontally(new_ncols, val);
1076    }
1077}
1078
1079// Move the elements of `data` in such a way that the matrix with
1080// the rows `[i, i + nremove[` deleted is represented in a contiguous
1081// way in `data` after this method completes.
1082// Every deleted element are manually dropped by this method.
1083unsafe fn compress_rows<T: Scalar>(
1084    data: &mut [T],
1085    nrows: usize,
1086    ncols: usize,
1087    i: usize,
1088    nremove: usize,
1089) {
1090    let new_nrows = nrows - nremove;
1091
1092    if nremove == 0 {
1093        return; // Nothing to remove or drop.
1094    }
1095
1096    if new_nrows == 0 || ncols == 0 {
1097        // The output matrix is empty, drop everything.
1098        ptr::drop_in_place(data);
1099        return;
1100    }
1101
1102    // Safety: because `nremove != 0`, the pointers given to `ptr::copy`
1103    //         won’t alias.
1104    let ptr_in = data.as_ptr();
1105    let ptr_out = data.as_mut_ptr();
1106
1107    let mut curr_i = i;
1108
1109    for k in 0..ncols - 1 {
1110        // Safety: we drop the row elements in-place because we will overwrite these
1111        //         entries later with the `ptr::copy`.
1112        let s = ptr::slice_from_raw_parts_mut(ptr_out.add(curr_i), nremove);
1113        ptr::drop_in_place(s);
1114        ptr::copy(
1115            ptr_in.add(curr_i + (k + 1) * nremove),
1116            ptr_out.add(curr_i),
1117            new_nrows,
1118        );
1119
1120        curr_i += new_nrows;
1121    }
1122
1123    /*
1124     * Deal with the last column from which less values have to be copied.
1125     */
1126    // Safety: we drop the row elements in-place because we will overwrite these
1127    //         entries later with the `ptr::copy`.
1128    let s = ptr::slice_from_raw_parts_mut(ptr_out.add(curr_i), nremove);
1129    ptr::drop_in_place(s);
1130    let remaining_len = nrows - i - nremove;
1131    ptr::copy(
1132        ptr_in.add(nrows * ncols - remaining_len),
1133        ptr_out.add(curr_i),
1134        remaining_len,
1135    );
1136}
1137
1138// Moves entries of a matrix buffer to make place for `ninsert` empty rows starting at the `i-th` row index.
1139// The `data` buffer is assumed to contained at least `(nrows + ninsert) * ncols` elements.
1140unsafe fn extend_rows<T>(data: &mut [T], nrows: usize, ncols: usize, i: usize, ninsert: usize) {
1141    let new_nrows = nrows + ninsert;
1142
1143    if new_nrows == 0 || ncols == 0 {
1144        return; // Nothing to do as the output matrix is empty.
1145    }
1146
1147    let ptr_in = data.as_ptr();
1148    let ptr_out = data.as_mut_ptr();
1149
1150    let remaining_len = nrows - i;
1151    let mut curr_i = new_nrows * ncols - remaining_len;
1152
1153    // Deal with the last column from which less values have to be copied.
1154    ptr::copy(
1155        ptr_in.add(nrows * ncols - remaining_len),
1156        ptr_out.add(curr_i),
1157        remaining_len,
1158    );
1159
1160    for k in (0..ncols - 1).rev() {
1161        curr_i -= new_nrows;
1162
1163        ptr::copy(ptr_in.add(k * nrows + i), ptr_out.add(curr_i), nrows);
1164    }
1165}
1166
1167/// Extend the number of columns of the `Matrix` with elements from
1168/// a given iterator.
1169#[cfg(any(feature = "std", feature = "alloc"))]
1170impl<T, R, S> Extend<T> for Matrix<T, R, Dyn, S>
1171where
1172    T: Scalar,
1173    R: Dim,
1174    S: Extend<T>,
1175{
1176    /// Extend the number of columns of the `Matrix` with elements
1177    /// from the given iterator.
1178    ///
1179    /// # Example
1180    /// ```
1181    /// # use nalgebra::{DMatrix, Dyn, Matrix, OMatrix, Matrix3};
1182    ///
1183    /// let data = vec![0, 1, 2,      // column 1
1184    ///                 3, 4, 5];     // column 2
1185    ///
1186    /// let mut matrix = DMatrix::from_vec(3, 2, data);
1187    ///
1188    /// matrix.extend(vec![6, 7, 8]); // column 3
1189    ///
1190    /// assert!(matrix.eq(&Matrix3::new(0, 3, 6,
1191    ///                                 1, 4, 7,
1192    ///                                 2, 5, 8)));
1193    /// ```
1194    ///
1195    /// # Panics
1196    /// This function panics if the number of elements yielded by the
1197    /// given iterator is not a multiple of the number of rows of the
1198    /// `Matrix`.
1199    ///
1200    /// ```should_panic
1201    /// # use nalgebra::{DMatrix, Dyn, OMatrix};
1202    /// let data = vec![0, 1, 2,  // column 1
1203    ///                 3, 4, 5]; // column 2
1204    ///
1205    /// let mut matrix = DMatrix::from_vec(3, 2, data);
1206    ///
1207    /// // The following panics because the vec length is not a multiple of 3.
1208    /// matrix.extend(vec![6, 7, 8, 9]);
1209    /// ```
1210    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1211        self.data.extend(iter);
1212    }
1213}
1214
1215/// Extend the number of rows of the `Vector` with elements from
1216/// a given iterator.
1217#[cfg(any(feature = "std", feature = "alloc"))]
1218impl<T, S> Extend<T> for Matrix<T, Dyn, U1, S>
1219where
1220    T: Scalar,
1221    S: Extend<T>,
1222{
1223    /// Extend the number of rows of a `Vector` with elements
1224    /// from the given iterator.
1225    ///
1226    /// # Example
1227    /// ```
1228    /// # use nalgebra::DVector;
1229    /// let mut vector = DVector::from_vec(vec![0, 1, 2]);
1230    /// vector.extend(vec![3, 4, 5]);
1231    /// assert!(vector.eq(&DVector::from_vec(vec![0, 1, 2, 3, 4, 5])));
1232    /// ```
1233    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1234        self.data.extend(iter);
1235    }
1236}
1237
1238#[cfg(any(feature = "std", feature = "alloc"))]
1239impl<T, R, S, RV, SV> Extend<Vector<T, RV, SV>> for Matrix<T, R, Dyn, S>
1240where
1241    T: Scalar,
1242    R: Dim,
1243    S: Extend<Vector<T, RV, SV>>,
1244    RV: Dim,
1245    SV: RawStorage<T, RV>,
1246    ShapeConstraint: SameNumberOfRows<R, RV>,
1247{
1248    /// Extends the number of columns of a `Matrix` with `Vector`s
1249    /// from a given iterator.
1250    ///
1251    /// # Example
1252    /// ```
1253    /// # use nalgebra::{DMatrix, Vector3, Matrix3x4};
1254    ///
1255    /// let data = vec![0, 1, 2,          // column 1
1256    ///                 3, 4, 5];         // column 2
1257    ///
1258    /// let mut matrix = DMatrix::from_vec(3, 2, data);
1259    ///
1260    /// matrix.extend(
1261    ///   vec![Vector3::new(6,  7,  8),   // column 3
1262    ///        Vector3::new(9, 10, 11)]); // column 4
1263    ///
1264    /// assert!(matrix.eq(&Matrix3x4::new(0, 3, 6,  9,
1265    ///                                   1, 4, 7, 10,
1266    ///                                   2, 5, 8, 11)));
1267    /// ```
1268    ///
1269    /// # Panics
1270    /// This function panics if the dimension of each `Vector` yielded
1271    /// by the given iterator is not equal to the number of rows of
1272    /// this `Matrix`.
1273    ///
1274    /// ```should_panic
1275    /// # use nalgebra::{DMatrix, Vector2, Matrix3x4};
1276    /// let mut matrix =
1277    ///   DMatrix::from_vec(3, 2,
1278    ///                     vec![0, 1, 2,   // column 1
1279    ///                          3, 4, 5]); // column 2
1280    ///
1281    /// // The following panics because this matrix can only be extended with 3-dimensional vectors.
1282    /// matrix.extend(
1283    ///   vec![Vector2::new(6,  7)]); // too few dimensions!
1284    /// ```
1285    ///
1286    /// ```should_panic
1287    /// # use nalgebra::{DMatrix, Vector4, Matrix3x4};
1288    /// let mut matrix =
1289    ///   DMatrix::from_vec(3, 2,
1290    ///                     vec![0, 1, 2,   // column 1
1291    ///                          3, 4, 5]); // column 2
1292    ///
1293    /// // The following panics because this matrix can only be extended with 3-dimensional vectors.
1294    /// matrix.extend(
1295    ///   vec![Vector4::new(6, 7, 8, 9)]); // too few dimensions!
1296    /// ```
1297    fn extend<I: IntoIterator<Item = Vector<T, RV, SV>>>(&mut self, iter: I) {
1298        self.data.extend(iter);
1299    }
1300}