rgsl/types/
matrix.rs

1//
2// A rust binding for the GSL library by Guillaume Gomez (guillaume1.gomez@gmail.com)
3//
4
5/*!
6# Matrices
7
8Matrices are defined by a gsl_matrix structure which describes a generalized slice of a block. Like a vector it represents a set of
9elements in an area of memory, but uses two indices instead of one.
10
11The gsl_matrix structure contains six components, the two dimensions of the matrix, a physical dimension, a pointer to the memory where
12the elements of the matrix are stored, data, a pointer to the block owned by the matrix block, if any, and an ownership flag, owner. The
13physical dimension determines the memory layout and can differ from the matrix dimension to allow the use of submatrices. The gsl_matrix
14structure is very simple and looks like this,
15
16```C
17typedef struct
18{
19  size_t size1;
20  size_t size2;
21  size_t tda;
22  double * data;
23  gsl_block * block;
24  int owner;
25} gsl_matrix;
26```
27
28Matrices are stored in row-major order, meaning that each row of elements forms a contiguous block in memory. This is the standard
29“C-language ordering” of two-dimensional arrays. Note that FORTRAN stores arrays in column-major order. The number of rows is size1. The
30range of valid row indices runs from 0 to size1-1. Similarly size2 is the number of columns. The range of valid column indices runs from
310 to size2-1. The physical row dimension tda, or trailing dimension, specifies the size of a row of the matrix as laid out in memory.
32
33For example, in the following matrix size1 is 3, size2 is 4, and tda is 8. The physical memory layout of the matrix begins in the top
34left hand-corner and proceeds from left to right along each row in turn.
35
3600 01 02 03 XX XX XX XX
3710 11 12 13 XX XX XX XX
3820 21 22 23 XX XX XX XX
39
40Each unused memory location is represented by “XX”. The pointer data gives the location of the first element of the matrix in memory. The
41pointer block stores the location of the memory block in which the elements of the matrix are located (if any). If the matrix owns this
42block then the owner field is set to one and the block will be deallocated when the matrix is freed. If the matrix is only a slice of a
43block owned by another object then the owner field is zero and any underlying block will not be freed.
44
45## References and Further Reading
46
47The block, vector and matrix objects in GSL follow the valarray model of C++. A description of this model can be found in the following
48reference,
49
50B. Stroustrup, The C++ Programming Language (3rd Ed), Section 22.4 Vector Arithmetic. Addison-Wesley 1997, ISBN 0-201-88954-4.
51!*/
52
53use crate::paste::paste;
54use crate::Value;
55use ffi::{self, FFI};
56use std::fmt::{self, Debug, Formatter};
57use std::marker::PhantomData;
58use types::{VectorF32, VectorF64, VectorI32, VectorU32};
59use types::{VectorF32View, VectorF64View, VectorI32View, VectorU32View};
60
61macro_rules! gsl_matrix {
62    ($rust_name:ident, $name:ident, $rust_ty:ident, $vec_name:ident, $vec_c_name:ident) => (
63paste! {
64pub struct $rust_name {
65    mat: *mut sys::$name,
66    can_free: bool,
67}
68
69impl $rust_name {
70    #[doc = "Creates a new " $rust_name " with all elements set to zero"]
71    #[doc(alias = $name _calloc)]
72    pub fn new(n1: usize, n2: usize) -> Option<$rust_name> {
73        let tmp = unsafe { sys::[<$name _calloc>](n1, n2) };
74
75        if tmp.is_null() {
76            None
77        } else {
78            Some(Self::wrap(tmp))
79        }
80    }
81
82    /// This function returns the (i,j)-th element of the matrix.
83    /// If y or x lie outside the allowed range of 0 to n1-1 and 0 to n2-1 then the error handler is
84    /// invoked and 0 is returned.
85    #[doc(alias = $name _get)]
86    pub fn get(&self, y: usize, x: usize) -> $rust_ty {
87        unsafe { sys::[<$name _get>](self.unwrap_shared(), y, x) }
88    }
89
90    /// This function sets the value of the (i,j)-th element of the matrix to value.
91    /// If y or x lies outside the allowed range of 0 to n1-1 and 0 to n2-1 then the error handler
92    /// is invoked.
93    #[doc(alias = $name _set)]
94    pub fn set(&mut self, y: usize, x: usize, value: $rust_ty) -> &$rust_name {
95        unsafe { sys::[<$name _set>](self.unwrap_unique(), y, x, value) };
96        self
97    }
98
99    /// This function sets all the elements of the matrix to the value x.
100    #[doc(alias = $name _set_all)]
101    pub fn set_all(&mut self, x: $rust_ty) -> &$rust_name {
102        unsafe { sys::[<$name _set_all>](self.unwrap_unique(), x) };
103        self
104    }
105
106    /// This function sets all the elements of the matrix to zero.
107    #[doc(alias = $name _set_zero)]
108    pub fn set_zero(&mut self) -> &$rust_name {
109        unsafe { sys::[<$name _set_zero>](self.unwrap_unique()) };
110        self
111    }
112
113    /// This function sets the elements of the matrix to the corresponding elements of the identity
114    /// matrix, m(i,j) = \delta(i,j), i.e. a unit diagonal with all off-diagonal elements zero.
115    /// This applies to both square and rectangular matrices.
116    #[doc(alias = $name _set_identity)]
117    pub fn set_identity(&mut self) -> &$rust_name {
118        unsafe { sys::[<$name _set_identity>](self.unwrap_unique()) };
119        self
120    }
121
122    /// This function copies the elements of the other matrix into the self matrix. The two matrices
123    /// must have the same size.
124    #[doc(alias = $name _memcpy)]
125    pub fn copy_from(&mut self, other: &$rust_name) -> Result<(), Value> {
126        let ret = unsafe { sys::[<$name _memcpy>](self.unwrap_unique(), other.unwrap_shared()) };
127        result_handler!(ret, ())
128    }
129
130    /// This function copies the elements of the self matrix into the other matrix. The two matrices
131    /// must have the same size.
132    #[doc(alias = $name _memcpy)]
133    pub fn copy_to(&self, other: &mut $rust_name) -> Result<(), Value> {
134        let ret = unsafe { sys::[<$name _memcpy>](other.unwrap_unique(), self.unwrap_shared()) };
135        result_handler!(ret, ())
136    }
137
138    /// This function exchanges the elements of the matrices self and other by copying. The two
139    /// matrices must have the same size.
140    #[doc(alias = $name _swap)]
141    pub fn swap(&mut self, other: &mut $rust_name) -> Result<(), Value> {
142        let ret = unsafe { sys::[<$name _swap>](self.unwrap_unique(), other.unwrap_unique()) };
143        result_handler!(ret, ())
144    }
145
146    /// This function copies the elements of the y-th row of the matrix into the returned vector.
147    #[doc(alias = $name _get_row)]
148    pub fn get_row(&self, y: usize) -> Result<$vec_name, Value> {
149        let tmp = unsafe { sys::[<$vec_c_name _alloc>](self.size2()) };
150
151        if tmp.is_null() {
152            Err(Value::NoMemory)
153        } else {
154            let ret = unsafe { sys::[<$name _get_row>](tmp, self.unwrap_shared(), y) };
155
156            result_handler!(ret, ffi::FFI::wrap(tmp))
157        }
158    }
159
160    /// This function copies the elements of the x-th column of the matrix into the returned vector.
161    #[doc(alias = $name _get_col)]
162    pub fn get_col(&self, x: usize) -> Result<$vec_name, Value> {
163        let tmp = unsafe { sys::[<$vec_c_name _alloc>](self.size1()) };
164
165        if tmp.is_null() {
166            Err(Value::NoMemory)
167        } else {
168            let ret = unsafe { sys::[<$name _get_col>](tmp, self.unwrap_shared(), x) };
169
170            result_handler!(ret, ffi::FFI::wrap(tmp))
171        }
172    }
173
174    /// This function copies the elements of the vector v into the y-th row of the matrix.
175    /// The length of the vector must be the same as the length of the row.
176    #[doc(alias = $name _set_row)]
177    pub fn set_row(&mut self, y: usize, v: &$vec_name) -> Result<(), Value> {
178        let ret = unsafe { sys::[<$name _set_row>](self.unwrap_unique(), y, v.unwrap_shared()) };
179        result_handler!(ret, ())
180    }
181
182    /// This function copies the elements of the vector v into the x-th column of the matrix.
183    /// The length of the vector must be the same as the length of the column.
184    #[doc(alias = $name _set_col)]
185    pub fn set_col(&mut self, x: usize, v: &$vec_name) -> Result<(), Value> {
186        let ret = unsafe { sys::[<$name _set_col>](self.unwrap_unique(), x, v.unwrap_shared()) };
187        result_handler!(ret, ())
188    }
189
190    /// This function exchanges the y1-th and y2-th rows of the matrix in-place.
191    #[doc(alias = $name _swap_rows)]
192    pub fn swap_rows(&mut self, y1: usize, y2: usize) -> Result<(), Value> {
193        let ret = unsafe { sys::[<$name _swap_rows>](self.unwrap_unique(), y1, y2) };
194        result_handler!(ret, ())
195    }
196
197    /// This function exchanges the x1-th and x2-th columns of the matrix in-place.
198    #[doc(alias = $name _swap_columns)]
199    pub fn swap_columns(&mut self, x1: usize, x2: usize) -> Result<(), Value> {
200        let ret = unsafe { sys::[<$name _swap_columns>](self.unwrap_unique(), x1, x2) };
201        result_handler!(ret, ())
202    }
203
204    /// This function exchanges the i-th row and j-th column of the matrix in-place.
205    /// The matrix must be square for this operation to be possible.
206    #[doc(alias = $name _swap_rowcol)]
207    pub fn swap_row_col(&mut self, i: usize, j: usize) -> Result<(), Value> {
208        let ret = unsafe { sys::[<$name _swap_rowcol>](self.unwrap_unique(), i, j) };
209        result_handler!(ret, ())
210    }
211
212    /// This function returns the transpose of the matrix by copying the elements into it.
213    /// This function works for all matrices provided that the dimensions of the matrix dest match
214    /// the transposed dimensions of the matrix.
215    #[doc(alias = $name _transpose_memcpy)]
216    pub fn transpose_memcpy(&self) -> Result<$rust_name, Value> {
217        let dest = unsafe { sys::[<$name _alloc>](self.size2(), self.size1()) };
218
219        if dest.is_null() {
220            Err(Value::NoMemory)
221        } else {
222            let ret = unsafe { sys::[<$name _transpose_memcpy>](dest, self.unwrap_shared()) };
223
224            result_handler!(ret, $rust_name::wrap(dest))
225        }
226    }
227
228    /// This function replaces the matrix m by its transpose by copying the elements of the matrix
229    /// in-place. The matrix must be square for this operation to be possible.
230    #[doc(alias = $name _transpose)]
231    pub fn transpose(&mut self) -> Result<(), Value> {
232        let ret = unsafe { sys::[<$name _transpose>](self.unwrap_unique()) };
233        result_handler!(ret, ())
234    }
235
236    /// This function adds the elements of the other matrix to the elements of the self matrix.
237    /// The result self(i,j) <- self(i,j) + other(i,j) is stored in self and other remains
238    /// unchanged. The two matrices must have the same dimensions.
239    #[doc(alias = $name _add)]
240    pub fn add(&mut self, other: &$rust_name) -> Result<(), Value> {
241        let ret = unsafe { sys::[<$name _add>](self.unwrap_unique(), other.unwrap_shared()) };
242        result_handler!(ret, ())
243    }
244
245    /// This function subtracts the elements of the other matrix from the elements of the self
246    /// matrix. The result self(i,j) <- self(i,j) - other(i,j) is stored in self and other remains
247    /// unchanged. The two matrices must have the same dimensions.
248    #[doc(alias = $name _sub)]
249    pub fn sub(&mut self, other: &$rust_name) -> Result<(), Value> {
250        let ret = unsafe { sys::[<$name _sub>](self.unwrap_unique(), other.unwrap_shared()) };
251        result_handler!(ret, ())
252    }
253
254    /// This function multiplies the elements of the self matrix by the elements of the other
255    /// matrix. The result self(i,j) <- self(i,j) * other(i,j) is stored in self and other remains
256    /// unchanged. The two matrices must have the same dimensions.
257    #[doc(alias = $name _mul_elements)]
258    pub fn mul_elements(&mut self, other: &$rust_name) -> Result<(), Value> {
259        let ret = unsafe {
260            sys::[<$name _mul_elements>](self.unwrap_unique(), other.unwrap_shared())
261        };
262        result_handler!(ret, ())
263    }
264
265    /// This function divides the elements of the self matrix by the elements of the other matrix.
266    /// The result self(i,j) <- self(i,j) / other(i,j) is stored in self and other remains
267    /// unchanged. The two matrices must have the same dimensions.
268    #[doc(alias = $name _div_elements)]
269    pub fn div_elements(&mut self, other: &$rust_name) -> Result<(), Value> {
270        let ret = unsafe {
271            sys::[<$name _div_elements>](self.unwrap_unique(), other.unwrap_shared())
272        };
273        result_handler!(ret, ())
274    }
275
276    /// This function multiplies the elements of the self matrix by the constant factor x. The
277    /// result self(i,j) <- x self(i,j) is stored in self.
278    #[doc(alias = $name _scale)]
279    pub fn scale(&mut self, x: $rust_ty) -> Result<(), Value> {
280        let ret = unsafe { sys::[<$name _scale>](self.unwrap_unique(), x) };
281        result_handler!(ret, ())
282    }
283
284    /// This function adds the constant value x to the elements of the self matrix. The result
285    /// self(i,j) <- self(i,j) + x is stored in self.
286    #[doc(alias = $name _add_constant)]
287    pub fn add_constant(&mut self, x: $rust_ty) -> Result<(), Value> {
288        let ret = unsafe { sys::[<$name _add_constant>](self.unwrap_unique(), x) };
289        result_handler!(ret, ())
290    }
291
292    #[doc(alias = $name _add_diagonal)]
293    pub fn add_diagonal(&mut self, x: $rust_ty) -> Result<(), Value> {
294        let ret = unsafe { sys::[<$name _add_diagonal>](self.unwrap_unique(), x) };
295        result_handler!(ret, ())
296    }
297
298    /// This function returns the maximum value in the self matrix.
299    #[doc(alias = $name _max)]
300    pub fn max(&self) -> $rust_ty {
301        unsafe { sys::[<$name _max>](self.unwrap_shared()) }
302    }
303
304    /// This function returns the minimum value in the self matrix.
305    #[doc(alias = $name _min)]
306    pub fn min(&self) -> $rust_ty {
307        unsafe { sys::[<$name _min>](self.unwrap_shared()) }
308    }
309
310    /// This function returns the minimum and maximum values in the self matrix.
311    #[doc(alias = $name _minmax)]
312    pub fn minmax(&self) -> ($rust_ty, $rust_ty) {
313        let mut min_out = 0 as _;
314        let mut max_out = 0 as _;
315        unsafe { sys::[<$name _minmax>](self.unwrap_shared(), &mut min_out, &mut max_out) };
316        (min_out, max_out)
317    }
318
319    /// This function returns the indices of the maximum value in the self matrix. When there are
320    /// several equal maximum elements then the first element found is returned, searching in
321    /// row-major order.
322    #[doc(alias = $name _max_index)]
323    pub fn max_index(&self) -> (usize, usize) {
324        let mut imax = 0;
325        let mut jmax = 0;
326
327        unsafe { sys::[<$name _max_index>](self.unwrap_shared(), &mut imax, &mut jmax) };
328        (imax, jmax)
329    }
330
331    /// This function returns the indices of the minimum value in the self matrix. When there are
332    /// several equal minimum elements then the first element found is returned, searching in row
333    /// major order.
334    #[doc(alias = $name _min_index)]
335    pub fn min_index(&self) -> (usize, usize) {
336        let mut imax = 0;
337        let mut jmax = 0;
338
339        unsafe { sys::[<$name _min_index>](self.unwrap_shared(), &mut imax, &mut jmax) };
340        (imax, jmax)
341    }
342
343    /// This function returns the indices of the minimum and maximum values in the self matrix. When
344    /// there are several equal minimum or maximum elements then the first elements found are
345    /// returned, searching in row-major order.
346    #[doc(alias = $name _minmax_index)]
347    pub fn minmax_index(&self) -> (usize, usize, usize, usize) {
348        let mut imin = 0;
349        let mut jmin = 0;
350        let mut imax = 0;
351        let mut jmax = 0;
352
353        unsafe {
354            sys::[<$name _minmax_index>](
355                self.unwrap_shared(),
356                &mut imin,
357                &mut jmin,
358                &mut imax,
359                &mut jmax,
360            )
361        };
362        (imin, jmin, imax, jmax)
363    }
364
365    /// This function returns true if all the elements of the self matrix are stricly zero.
366    #[doc(alias = $name _isnull)]
367    pub fn is_null(&self) -> bool {
368        unsafe { sys::[<$name _isnull>](self.unwrap_shared()) == 1 }
369    }
370
371    /// This function returns true if all the elements of the self matrix are stricly positive.
372    #[doc(alias = $name _ispos)]
373    pub fn is_pos(&self) -> bool {
374        unsafe { sys::[<$name _ispos>](self.unwrap_shared()) == 1 }
375    }
376
377    /// This function returns true if all the elements of the self matrix are stricly negative.
378    #[doc(alias = $name _isneg)]
379    pub fn is_neg(&self) -> bool {
380        unsafe { sys::[<$name _isneg>](self.unwrap_shared()) == 1 }
381    }
382
383    /// This function returns true if all the elements of the self matrix are stricly non-negative.
384    #[doc(alias = $name _isnonneg)]
385    pub fn is_non_neg(&self) -> bool {
386        unsafe { sys::[<$name _isnonneg>](self.unwrap_shared()) == 1 }
387    }
388
389    /// This function returns true if all elements of the two matrix are equal.
390    #[doc(alias = $name _equal)]
391    pub fn equal(&self, other: &$rust_name) -> bool {
392        unsafe { sys::[<$name _equal>](self.unwrap_shared(), other.unwrap_shared()) == 1 }
393    }
394
395    #[doc(alias = $name _row)]
396    pub fn row<F: FnOnce(Option<[<$vec_name View>]>)>(&mut self, i: usize, f: F) {
397        [<$vec_name View>]::wrap(unsafe { sys::[<$name _row>](self.unwrap_unique(), i) }, f)
398    }
399
400    #[doc(alias = $name _column)]
401    pub fn column<F: FnOnce(Option<[<$vec_name View>]>)>(&mut self, j: usize, f: F) {
402        [<$vec_name View>]::wrap(unsafe { sys::[<$name _column>](self.unwrap_unique(), j) }, f)
403    }
404
405    #[doc(alias = $name _diagonal)]
406    pub fn diagonal<F: FnOnce(Option<[<$vec_name View>]>)>(&mut self, f: F) {
407        [<$vec_name View>]::wrap(unsafe { sys::[<$name _diagonal>](self.unwrap_unique()) }, f)
408    }
409
410    #[doc(alias = $name _subdiagonal)]
411    pub fn subdiagonal<F: FnOnce(Option<[<$vec_name View>]>)>(&mut self, k: usize, f: F) {
412        [<$vec_name View>]::wrap(unsafe { sys::[<$name _subdiagonal>](self.unwrap_unique(), k) }, f)
413    }
414
415    #[doc(alias = $name _superdiagonal)]
416    pub fn superdiagonal<F: FnOnce(Option<[<$vec_name View>]>)>(&mut self, k: usize, f: F) {
417        [<$vec_name View>]::wrap(unsafe { sys::[<$name _superdiagonal>](self.unwrap_unique(), k) }, f)
418    }
419
420    #[doc(alias = $name _subrow)]
421    pub fn subrow<F: FnOnce(Option<[<$vec_name View>]>)>(&mut self, i: usize, offset: usize, n: usize, f: F) {
422        [<$vec_name View>]::wrap(unsafe { sys::[<$name _subrow>](self.unwrap_unique(), i, offset, n) }, f)
423    }
424
425    #[doc(alias = $name _subcolumn)]
426    pub fn subcolumn<F: FnOnce(Option<[<$vec_name View>]>)>(&mut self, i: usize, offset: usize, n: usize, f: F) {
427        [<$vec_name View>]::wrap(unsafe { sys::[<$name _subcolumn>](self.unwrap_unique(), i, offset, n) }, f)
428    }
429
430    #[doc(alias = $name _submatrix)]
431    pub fn submatrix(
432        &mut self,
433        k1: usize,
434        k2: usize,
435        n1: usize,
436        n2: usize,
437    ) -> [<$rust_name View>]<'_> {
438        [<$rust_name View>]::from_matrix(self, k1, k2, n1, n2)
439    }
440
441    pub fn size1(&self) -> usize {
442        if self.unwrap_shared().is_null() {
443            0
444        } else {
445            unsafe { (*self.unwrap_shared()).size1 }
446        }
447    }
448
449    pub fn size2(&self) -> usize {
450        if self.unwrap_shared().is_null() {
451            0
452        } else {
453            unsafe { (*self.unwrap_shared()).size2 }
454        }
455    }
456
457    pub fn clone(&self) -> Option<Self> {
458        if self.unwrap_shared().is_null() {
459            None
460        } else {
461            if let Some(mut m) = Self::new(self.size1(), self.size2()) {
462                if m.copy_from(self).is_err() {
463                    None
464                } else {
465                    Some(m)
466                }
467            } else {
468                None
469            }
470        }
471    }
472
473    #[doc(hidden)]
474    pub fn is_ptr_null(&self) -> bool {
475        self.unwrap_shared().is_null()
476    }
477}
478
479impl Drop for $rust_name {
480    #[doc(alias = $name _free)]
481    fn drop(&mut self) {
482        if self.can_free {
483            unsafe { sys::[<$name _free>](self.mat) };
484            self.mat = std::ptr::null_mut();
485        }
486    }
487}
488
489impl FFI<sys::$name> for $rust_name {
490    fn wrap(mat: *mut sys::$name) -> Self {
491        Self {
492            mat,
493            can_free: true,
494        }
495    }
496
497    fn soft_wrap(mat: *mut sys::$name) -> Self {
498        Self {
499            mat,
500            can_free: false,
501        }
502    }
503
504    fn unwrap_shared(&self) -> *const sys::$name {
505        self.mat as *const _
506    }
507
508    fn unwrap_unique(&mut self) -> *mut sys::$name {
509        self.mat
510    }
511}
512
513impl Debug for $rust_name {
514    #[allow(unused_must_use)]
515    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
516        let ptr = self.unwrap_shared();
517        if ptr.is_null() {
518            write!(f, "<null>")
519        } else {
520            let size1 = self.size1();
521            let size2 = self.size2();
522            for y in 0..size1 {
523                write!(f, "[");
524                for x in 0..size2 {
525                    if x < size2 - 1 {
526                        write!(f, "{}, ", self.get(y, x));
527                    } else {
528                        write!(f, "{}", self.get(y, x));
529                    }
530                }
531                if y < size1 - 1 {
532                    write!(f, "]\n");
533                }
534            }
535            write!(f, "]")
536        }
537    }
538}
539
540pub struct [<$rust_name View>]<'a> {
541    mat: sys::[<$name _view>],
542    #[allow(dead_code)]
543    phantom: PhantomData<&'a ()>,
544}
545
546impl<'a> [<$rust_name View>]<'a> {
547    /// These functions return a matrix view of a submatrix of the matrix m. The upper-left element
548    /// of the submatrix is the element (k1,k2) of the original matrix. The submatrix has n1 rows
549    /// and n2 columns. The physical number of columns in memory given by tda is unchanged.
550    /// Mathematically, the (i,j)-th element of the new matrix is given by,
551    ///
552    /// m'(i,j) = m->data[(k1*m->tda + k2) + i*m->tda + j]
553    ///
554    /// where the index i runs from 0 to n1-1 and the index j runs from 0 to n2-1.
555    ///
556    /// The data pointer of the returned matrix struct is set to null if the combined parameters
557    /// (i,j,n1,n2,tda) overrun the ends of the original
558    /// matrix.
559    ///
560    /// The new matrix view is only a view of the block underlying the existing matrix, m. The
561    /// block containing the elements of m is not
562    /// owned by the new matrix view. When the view goes out of scope the original matrix m and its
563    /// block will continue to exist. The original memory can only be deallocated by freeing the
564    /// original matrix. Of course, the original matrix should not be deallocated while the view
565    /// is still in use.
566    ///
567    /// The function gsl_matrix_const_submatrix is equivalent to gsl_matrix_submatrix but can be
568    /// used for matrices which are declared const.
569    #[doc(alias = $name _submatrix)]
570    pub fn from_matrix(
571        m: &'a mut $rust_name,
572        k1: usize,
573        k2: usize,
574        n1: usize,
575        n2: usize,
576    ) -> Self {
577        unsafe {
578            Self {
579                mat: sys::[<$name _submatrix>](m.mat, k1, k2, n1, n2),
580                phantom: PhantomData,
581            }
582        }
583    }
584
585    /// These functions return a matrix view of the array base. The matrix has n1 rows and n2
586    /// columns. The physical number of columns in memory is also given by n2. Mathematically, the
587    /// (i,j)-th element of the new matrix is given by,
588    ///
589    /// m'(i,j) = base[i*n2 + j]
590    ///
591    /// where the index i runs from 0 to n1-1 and the index j runs from 0 to n2-1.
592    ///
593    /// The new matrix is only a view of the array base. When the view goes out of scope the
594    /// original array base will continue to exist. The original memory can only be deallocated by
595    /// freeing the original array. Of course, the original array should not be deallocated while
596    /// the view is still in use.
597    ///
598    /// The function gsl_matrix_const_view_array is equivalent to gsl_matrix_view_array but can be
599    /// used for matrices which are declared const.
600    #[doc(alias = $name _view_array)]
601    pub fn from_array(base: &'a mut [$rust_ty], n1: usize, n2: usize) -> Self {
602        assert!(
603            n1 * n2 <= base.len() as _,
604            "n1 * n2 cannot be longer than base"
605        );
606        unsafe {
607            Self {
608                mat: sys::[<$name _view_array>](base.as_mut_ptr(), n1, n2),
609                phantom: PhantomData,
610            }
611        }
612    }
613
614    /// These functions return a matrix view of the array base with a physical number of columns tda
615    /// which may differ from the corresponding dimension of the matrix. The matrix has n1 rows and
616    /// n2 columns, and the physical number of columns in memory is given by tda. Mathematically,
617    /// the (i,j)-th element of the new matrix is given by,
618    ///
619    /// m'(i,j) = base[i*tda + j]
620    ///
621    /// where the index i runs from 0 to n1-1 and the index j runs from 0 to n2-1.
622    ///
623    /// The new matrix is only a view of the array base. When the view goes out of scope the
624    /// original array base will continue to exist. The original memory can only be deallocated by
625    /// freeing the original array. Of course, the original array should not be deallocated while
626    /// the view is still in use.
627    ///
628    /// The function gsl_matrix_const_view_array_with_tda is equivalent to
629    /// gsl_matrix_view_array_with_tda but can be used for matrices which are declared const.
630    #[doc(alias = $name _view_array_with_tda)]
631    pub fn from_array_with_tda(base: &'a mut [$rust_ty], n1: usize, n2: usize, tda: usize) -> Self {
632        unsafe {
633            Self {
634                mat: sys::[<$name _view_array_with_tda>](base.as_mut_ptr(), n1, n2, tda),
635                phantom: PhantomData,
636            }
637        }
638    }
639
640    /// These functions return a matrix view of the vector v. The matrix has n1 rows and n2 columns.
641    /// The vector must have unit stride. The physical number of columns in memory is also given by
642    /// n2. Mathematically, the (i,j)-th element of the new matrix is given by,
643    ///
644    /// m'(i,j) = v->data[i*n2 + j]
645    ///
646    /// where the index i runs from 0 to n1-1 and the index j runs from 0 to n2-1.
647    ///
648    /// The new matrix is only a view of the vector v. When the view goes out of scope the original
649    /// vector v will continue to exist. The original memory can only be deallocated by freeing the
650    /// original vector. Of course, the original vector should not be deallocated while the view
651    /// is still in use.
652    ///
653    /// The function gsl_matrix_const_view_vector is equivalent to gsl_matrix_view_vector but can be
654    /// used for matrices which are declared const.
655    #[doc(alias = $name _view_vector)]
656    pub fn from_vector(v: &'a mut $vec_name, n1: usize, n2: usize) -> Self {
657        unsafe {
658            Self {
659                mat: sys::[<$name _view_vector>](v.unwrap_unique(), n1, n2),
660                phantom: PhantomData,
661            }
662        }
663    }
664
665    /// These functions return a matrix view of the vector v with a physical number of columns tda
666    /// which may differ from the corresponding matrix dimension. The vector must have unit stride.
667    /// The matrix has n1 rows and n2 columns, and the physical number of columns in memory is given
668    /// by tda. Mathematically, the (i,j)-th element of the new matrix is given by,
669    ///
670    /// m'(i,j) = v->data[i*tda + j]
671    ///
672    /// where the index i runs from 0 to n1-1 and the index j runs from 0 to n2-1.
673    ///
674    /// The new matrix is only a view of the vector v. When the view goes out of scope the original
675    /// vector v will continue to exist. The original memory can only be deallocated by freeing the
676    /// original vector. Of course, the original vector should not be deallocated while the view
677    /// is still in use.
678    ///
679    /// The function gsl_matrix_const_view_vector_with_tda is equivalent to
680    /// gsl_matrix_view_vector_with_tda but can be used for matrices which are declared const.
681    #[doc(alias = $name _view_vector_with_tda)]
682    pub fn from_vector_with_tda(v: &'a mut $vec_name, n1: usize, n2: usize, tda: usize) -> Self {
683        unsafe {
684            Self {
685                mat: sys::[<$name _view_vector_with_tda>](v.unwrap_unique(), n1, n2, tda),
686                phantom: PhantomData,
687            }
688        }
689    }
690
691    pub fn matrix<F: FnOnce(Option<&$rust_name>)>(&self, f: F) {
692        let tmp = &self.mat.matrix;
693        let tmp_mat = $rust_name::soft_wrap(tmp as *const _ as usize as *mut _);
694        if tmp_mat.is_ptr_null() {
695            f(None)
696        } else {
697            f(Some(&tmp_mat))
698        }
699    }
700
701    pub fn matrix_mut<F: FnOnce(Option<&mut $rust_name>)>(&mut self, f: F) {
702        let tmp = &mut self.mat.matrix;
703        let mut tmp_mat = $rust_name::soft_wrap(tmp as *mut _);
704        if tmp_mat.is_ptr_null() {
705            f(None)
706        } else {
707            f(Some(&mut tmp_mat))
708        }
709    }
710} // end of impl block
711} // end of paste! block
712
713    ); // end of the gsl_matrix macro
714}
715
716gsl_matrix!(
717    MatrixF32,
718    gsl_matrix_float,
719    f32,
720    VectorF32,
721    gsl_vector_float
722);
723gsl_matrix!(MatrixF64, gsl_matrix, f64, VectorF64, gsl_vector);
724gsl_matrix!(MatrixI32, gsl_matrix_int, i32, VectorI32, gsl_vector_int);
725gsl_matrix!(MatrixU32, gsl_matrix_uint, u32, VectorU32, gsl_vector_uint);