vnl_matrix.h
Go to the documentation of this file.
1 // This is core/vnl/vnl_matrix.h
2 #ifndef vnl_matrix_h_
3 #define vnl_matrix_h_
4 #ifdef __INTEL_COMPILER
5 #pragma warning disable 444
6 #endif
7 //:
8 // \file
9 // \brief An ordinary mathematical matrix
10 // \verbatim
11 // Modifications
12 // Apr 21, 1989 - MBN - Initial design and implementation
13 // Jun 22, 1989 - MBN - Removed non-destructive methods
14 // Aug 09, 1989 - LGO - Inherit from Generic
15 // Aug 20, 1989 - MBN - Changed template usage to reflect new syntax
16 // Sep 11, 1989 - MBN - Added conditional exception handling and base class
17 // Oct 05, 1989 - LGO - Don't re-allocate data in operator= when same size
18 // Oct 19, 1989 - LGO - Add extra parameter to varargs constructor
19 // Oct 19, 1989 - MBN - Added optional argument to set_compare method
20 // Dec 08, 1989 - LGO - Allocate column data in one chunk
21 // Dec 08, 1989 - LGO - Clean-up get and put, add const everywhere.
22 // Dec 19, 1989 - LGO - Remove the map and reduce methods
23 // Feb 22, 1990 - MBN - Changed size arguments from int to unsigned int
24 // Jun 30, 1990 - MJF - Added base class name to constructor initializer
25 // Feb 21, 1992 - VDN - New lite version
26 // May 05, 1992 - VDN - Use envelope to avoid unnecessary copying
27 // Sep 30, 1992 - VDN - Matrix inversion with singular value decomposition
28 // Aug 21, 1996 - AWF - set_identity, normalize_rows, scale_row.
29 // Sep 30, 1996 - AWF - set_row/column methods. Const-correct data_block().
30 // 14 Feb 1997 - AWF - get_n_rows, get_n_columns.
31 // 20 Mar 1997 - PVR - get_row, get_column.
32 // 24-Oct-2010 - Peter Vanroose - mutators and filling methods now return *this
33 // 18-Jan-2011 - Peter Vanroose - added methods set_diagonal() & get_diagonal()
34 // \endverbatim
35 
36 #include <iosfwd>
37 #include <vcl_compiler.h>
38 #ifdef _MSC_VER
39 # include <vcl_msvc_warnings.h>
40 #endif
41 #include <vnl/vnl_tag.h>
42 #include <vnl/vnl_c_vector.h>
43 #include <vnl/vnl_config.h>
44 #include <vnl/vnl_error.h>
45 #ifndef NDEBUG
46 # if VNL_CONFIG_CHECK_BOUNDS
47 #include <cassert>
48 # endif
49 #else
50 # undef VNL_CONFIG_CHECK_BOUNDS
51 # define VNL_CONFIG_CHECK_BOUNDS 0
52 # undef ERROR_CHECKING
53 #endif
54 #include "vnl/vnl_export.h"
55 
56 template <class T> class vnl_vector;
57 template <class T> class vnl_matrix;
58 
59 //--------------------------------------------------------------------------------
60 
61 #ifndef DOXYGEN_SHOULD_SKIP_THIS
62 #define v vnl_vector<T>
63 #define m vnl_matrix<T>
64 #endif // DOXYGEN_SHOULD_SKIP_THIS
65 template <class T> VNL_EXPORT m operator+(T const&, m const&);
66 template <class T> VNL_EXPORT m operator-(T const&, m const&);
67 template <class T> VNL_EXPORT m operator*(T const&, m const&);
68 template <class T> VNL_EXPORT m element_product(m const&, m const&);
69 template <class T> VNL_EXPORT m element_quotient(m const&, m const&);
70 template <class T> VNL_EXPORT T dot_product(m const&, m const&);
71 template <class T> VNL_EXPORT T inner_product(m const&, m const&);
72 template <class T> VNL_EXPORT T cos_angle(m const&, m const& );
73 template <class T> VNL_EXPORT std::ostream& operator<<(std::ostream&, m const&);
74 template <class T> VNL_EXPORT std::istream& operator>>(std::istream&, m&);
75 #undef v
76 #undef m
77 
78 //--------------------------------------------------------------------------------
79 
80 enum VNL_EXPORT vnl_matrix_type
81 {
83  vnl_matrix_identity
84 };
85 
86 //: An ordinary mathematical matrix
87 // The vnl_matrix<T> class implements two-dimensional arithmetic
88 // matrices for a user-specified numeric data type. Using the
89 // parameterized types facility of C++, it is possible, for
90 // example, for the user to create a matrix of rational numbers
91 // by parameterizing the vnl_matrix class over the Rational class.
92 // The only requirement for the type is that it supports the
93 // basic arithmetic operators.
94 //
95 // Note: Unlike the other sequence classes, the
96 // vnl_matrix<T> class is fixed-size. It will not grow once the
97 // size has been specified to the constructor or changed by the
98 // assignment or multiplication operators. The vnl_matrix<T>
99 // class is row-based with addresses of rows being cached, and
100 // elements accessed as m[row][col].
101 //
102 // Note: The matrix can, however, be resized using the set_size(nr,nc) function.
103 //
104 // Note: Indexing of the matrix is zero-based, so the top-left element is M(0,0).
105 //
106 // Note: Inversion of matrix M, and other operations such as solving systems of linear
107 // equations are handled by the matrix decomposition classes in vnl/algo, such
108 // as matrix_inverse, svd, qr etc.
109 //
110 // Note: Use a vnl_vector<T> with these matrices.
111 
112 template<class T>
113 class VNL_EXPORT vnl_matrix
114 {
115  public:
116  //: Default constructor creates an empty matrix of size 0,0.
118  num_rows(0),
119  num_cols(0),
120  data(nullptr)
121  {
122  }
123 
124  //: Construct a matrix of size r rows by c columns
125  // Contents are unspecified.
126  // Complexity $O(1)$
127  vnl_matrix(unsigned r, unsigned c); // r rows, c cols.
128 
129  //: Construct a matrix of size r rows by c columns, and all elements equal to v0
130  // Complexity $O(r.c)$
131  vnl_matrix(unsigned r, unsigned c, T const& v0); // r rows, c cols, value v0.
132 
133  //: Construct a matrix of size r rows by c columns, with a special type
134  // Contents are specified by t
135  // Complexity $O(r.c)$
136  vnl_matrix(unsigned r, unsigned c, vnl_matrix_type t); // r rows, c cols, special type
137 
138  //: Construct a matrix of size r rows by c columns, initialised by an automatic array
139  // The first n elements, are initialised row-wise, to values.
140  // Complexity $O(n)$
141  vnl_matrix(unsigned r, unsigned c, unsigned n, T const values[]); // use automatic arrays.
142 
143  //: Construct a matrix of size r rows by c columns, initialised by a memory block
144  // The values are initialise row wise from the data.
145  // Complexity $O(r.c)$
146  vnl_matrix(T const* data_block, unsigned r, unsigned c); // fill row-wise.
147 
148  //: Copy construct a matrix
149  // Complexity $O(r.c)$
150  vnl_matrix(vnl_matrix<T> const&); // from another matrix.
151 
152 #ifndef VXL_DOXYGEN_SHOULD_SKIP_THIS
153 // <internal>
154  // These constructors are here so that operator* etc can take
155  // advantage of the C++ return value optimization.
156  vnl_matrix(vnl_matrix<T> const &, vnl_matrix<T> const &, vnl_tag_add); // M + M
157  vnl_matrix(vnl_matrix<T> const &, vnl_matrix<T> const &, vnl_tag_sub); // M - M
158  vnl_matrix(vnl_matrix<T> const &, T, vnl_tag_mul); // M * s
159  vnl_matrix(vnl_matrix<T> const &, T, vnl_tag_div); // M / s
160  vnl_matrix(vnl_matrix<T> const &, T, vnl_tag_add); // M + s
161  vnl_matrix(vnl_matrix<T> const &, T, vnl_tag_sub); // M - s
162  vnl_matrix(vnl_matrix<T> const &, vnl_matrix<T> const &, vnl_tag_mul); // M * M
164  : num_rows(that.num_rows), num_cols(that.num_cols), data(that.data)
165  { that.num_cols=that.num_rows=0; that.data=nullptr; } // "*this" now uses "that"'s data.
166 // </internal>
167 #endif
168 
169  //: Matrix destructor
170  ~vnl_matrix();
171 
172 // Basic 2D-Array functionality-------------------------------------------
173 
174  //: Return the total number of elements stored by the matrix.
175  // This equals rows() * cols()
176  inline unsigned int size() const { return this->num_rows*this->num_cols; }
177 
178  //: Return the number of rows.
179  inline unsigned int rows() const { return this->num_rows; }
180 
181  //: Return the number of columns.
182  // A synonym for columns().
183  inline unsigned int cols() const { return this->num_cols; }
184 
185  //: Return the number of columns.
186  // A synonym for cols().
187  inline unsigned int columns() const { return this->num_cols; }
188 
189  //: set element with boundary checks if error checking is on.
190  inline void put(unsigned r, unsigned c, T const&);
191 
192  //: get element with boundary checks if error checking is on.
193  inline T get(unsigned r, unsigned c) const;
194 
195  //: return pointer to given row
196  // No boundary checking here.
197  T * operator[](unsigned r) { return data[r]; }
198 
199  //: return pointer to given row
200  // No boundary checking here.
201  T const * operator[](unsigned r) const { return data[r]; }
202 
203  //: Access an element for reading or writing
204  // There are assert style boundary checks - #define NDEBUG to turn them off.
205  T & operator()(unsigned r, unsigned c);
206 
207  //: Access an element for reading
208  // There are assert style boundary checks - #define NDEBUG to turn them off.
209  T const & operator()(unsigned r, unsigned c) const;
210 
211 
212  // ----------------------- Filling and copying -----------------------
213 
214  //: Sets all elements of matrix to specified value, and returns "*this".
215  // Complexity $O(r.c)$
216  // Returning "*this" allows "chaining" two or more operations:
217  // e.g., to set a matrix to a column-normalized all-elements-equal matrix, say
218  // \code
219  // M.fill(1).normalize_columns();
220  // \endcode
221  // Returning "*this" also allows passing such a matrix as argument
222  // to a function f, without having to name the constructed matrix:
223  // \code
224  // f(vnl_matrix<double>(5,5,1.0).normalize_columns());
225  // \endcode
226  vnl_matrix& fill(T const&);
227 
228  //: Sets all diagonal elements of matrix to specified value; returns "*this".
229  // Complexity $O(\min(r,c))$
230  // Returning "*this" allows "chaining" two or more operations:
231  // e.g., to set a 3x3 matrix to [5 0 0][0 10 0][0 0 15], just say
232  // \code
233  // M.fill_diagonal(5).scale_row(1,2).scale_column(2,3);
234  // \endcode
235  // Returning "*this" also allows passing a diagonal-filled matrix as argument
236  // to a function f, without having to name the constructed matrix:
237  // \code
238  // f(vnl_matrix<double>(3,3).fill_diagonal(5));
239  // \endcode
240  vnl_matrix& fill_diagonal(T const&);
241 
242  //: Sets the diagonal elements of this matrix to the specified list of values.
243  // Returning "*this" allows "chaining" two or more operations: see the
244  // reasoning (and the examples) in the documentation for method
245  // fill_diagonal().
246  vnl_matrix& set_diagonal(vnl_vector<T> const&);
247 
248  //: Fills (laminates) this matrix with the given data, then returns it.
249  // We assume that the argument points to a contiguous rows*cols array, stored rowwise.
250  // No bounds checking on the array.
251  // Returning "*this" allows "chaining" two or more operations:
252  // e.g., to fill a square matrix column-wise, fill it rowwise then transpose:
253  // \code
254  // M.copy_in(array).inplace_transpose();
255  // \endcode
256  // Returning "*this" also allows passing a filled-in matrix as argument
257  // to a function f, without having to name the constructed matrix:
258  // \code
259  // f(vnl_matrix<double>(3,3).copy_in(array));
260  // \endcode
261  vnl_matrix& copy_in(T const *);
262 
263  //: Fills (laminates) this matrix with the given data, then returns it.
264  // A synonym for copy_in()
265  vnl_matrix& set(T const *d) { return copy_in(d); }
266 
267  //: Fills the given array with this matrix.
268  // We assume that the argument points to a contiguous rows*cols array, stored rowwise.
269  // No bounds checking on the array.
270  void copy_out(T *) const;
271 
272  //: Set all elements to value v
273  // Complexity $O(r.c)$
274  vnl_matrix<T>& operator=(T const&v) { fill(v); return *this; }
275 
276  //: Copies all elements of rhs matrix into lhs matrix.
277  // Complexity $O(\min(r,c))$
278  vnl_matrix<T>& operator=(vnl_matrix<T> const&);
279 
280  // ----------------------- Arithmetic --------------------------------
281  // note that these functions should not pass scalar as a const&.
282  // Look what would happen to A /= A(0,0).
283 
284  //: Add rhs to each element of lhs matrix in situ
285  vnl_matrix<T>& operator+=(T value);
286 
287  //: Subtract rhs from each element of lhs matrix in situ
288  vnl_matrix<T>& operator-=(T value);
289 
290  //: Scalar multiplication in situ of lhs matrix by rhs
291  vnl_matrix<T>& operator*=(T value);
292 
293  //: Scalar division of lhs matrix in situ by rhs
294  vnl_matrix<T>& operator/=(T value);
295 
296  //: Add rhs to lhs matrix in situ
297  vnl_matrix<T>& operator+=(vnl_matrix<T> const&);
298  //: Subtract rhs from lhs matrix in situ
299  vnl_matrix<T>& operator-=(vnl_matrix<T> const&);
300  //: Multiply lhs matrix in situ by rhs
301  vnl_matrix<T>& operator*=(vnl_matrix<T> const&rhs) { return *this = (*this) * rhs; }
302 
303  //: Negate all elements of matrix
304  vnl_matrix<T> operator-() const;
305 
306 
307  //: Add rhs to each element of lhs matrix and return result in new matrix
308  vnl_matrix<T> operator+(T const& v) const { return vnl_matrix<T>(*this, v, vnl_tag_add()); }
309 
310  //: Subtract rhs from each element of lhs matrix and return result in new matrix
311  vnl_matrix<T> operator-(T const& v) const { return vnl_matrix<T>(*this, v, vnl_tag_sub()); }
312 
313  //: Scalar multiplication of lhs matrix by rhs and return result in new matrix
314  vnl_matrix<T> operator*(T const& v) const { return vnl_matrix<T>(*this, v, vnl_tag_mul()); }
315 
316  //: Scalar division of lhs matrix by rhs and return result in new matrix
317  vnl_matrix<T> operator/(T const& v) const { return vnl_matrix<T>(*this, v, vnl_tag_div()); }
318 
319  //: Matrix add rhs to lhs matrix and return result in new matrix
320  vnl_matrix<T> operator+(vnl_matrix<T> const& rhs) const { return vnl_matrix<T>(*this, rhs, vnl_tag_add()); }
321  //: Matrix subtract rhs from lhs and return result in new matrix
322  vnl_matrix<T> operator-(vnl_matrix<T> const& rhs) const { return vnl_matrix<T>(*this, rhs, vnl_tag_sub()); }
323  //: Matrix multiply lhs by rhs matrix and return result in new matrix
324  vnl_matrix<T> operator*(vnl_matrix<T> const& rhs) const { return vnl_matrix<T>(*this, rhs, vnl_tag_mul()); }
325 
326  ////--------------------------- Additions ----------------------------
327 
328  //: Make a new matrix by applying function to each element.
329  vnl_matrix<T> apply(T (*f)(T)) const;
330 
331  //: Make a new matrix by applying function to each element.
332  vnl_matrix<T> apply(T (*f)(T const&)) const;
333 
334  //: Make a vector by applying a function across rows.
335  vnl_vector<T> apply_rowwise(T (*f)(vnl_vector<T> const&)) const;
336 
337  //: Make a vector by applying a function across columns.
338  vnl_vector<T> apply_columnwise(T (*f)(vnl_vector<T> const&)) const;
339 
340  //: Return transpose
341  vnl_matrix<T> transpose() const;
342 
343  //: Return conjugate transpose
344  vnl_matrix<T> conjugate_transpose() const;
345 
346  //: Set values of this matrix to those of M, starting at [top,left]
347  vnl_matrix<T>& update(vnl_matrix<T> const&, unsigned top=0, unsigned left=0);
348 
349  //: Set the elements of the i'th column to v[i] (No bounds checking)
350  vnl_matrix& set_column(unsigned i, T const * v);
351 
352  //: Set the elements of the i'th column to value, then return *this.
353  vnl_matrix& set_column(unsigned i, T value );
354 
355  //: Set j-th column to v, then return *this.
356  vnl_matrix& set_column(unsigned j, vnl_vector<T> const& v);
357 
358  //: Set columns to those in M, starting at starting_column, then return *this.
359  vnl_matrix& set_columns(unsigned starting_column, vnl_matrix<T> const& M);
360 
361  //: Set the elements of the i'th row to v[i] (No bounds checking)
362  vnl_matrix& set_row(unsigned i, T const * v);
363 
364  //: Set the elements of the i'th row to value, then return *this.
365  vnl_matrix& set_row(unsigned i, T value );
366 
367  //: Set the i-th row
368  vnl_matrix& set_row(unsigned i, vnl_vector<T> const&);
369 
370  //: Extract a sub-matrix of size r x c, starting at (top,left)
371  // Thus it contains elements [top,top+r-1][left,left+c-1]
372  vnl_matrix<T> extract(unsigned r, unsigned c,
373  unsigned top=0, unsigned left=0) const;
374 
375  //: Extract a sub-matrix starting at (top,left)
376  //
377  // The output is stored in \a sub_matrix, and it should have the
378  // required size on entry. Thus the result will contain elements
379  // [top,top+sub_matrix.rows()-1][left,left+sub_matrix.cols()-1]
380  void extract ( vnl_matrix<T>& sub_matrix,
381  unsigned top=0, unsigned left=0) const;
382 
383 
384  //: Get a vector equal to the given row
385  vnl_vector<T> get_row(unsigned r) const;
386 
387  //: Get a vector equal to the given column
388  vnl_vector<T> get_column(unsigned c) const;
389 
390  //: Get a matrix composed of rows from the indices specified in the supplied vector.
391  vnl_matrix<T> get_rows(vnl_vector<unsigned int> i) const;
392 
393  //: Get a matrix composed of columns from the indices specified in the supplied vector.
394  vnl_matrix<T> get_columns(vnl_vector<unsigned int> i) const;
395 
396  //: Get n rows beginning at rowstart
397  vnl_matrix<T> get_n_rows(unsigned rowstart, unsigned n) const;
398 
399  //: Get n columns beginning at colstart
400  vnl_matrix<T> get_n_columns(unsigned colstart, unsigned n) const;
401 
402  //: Return a vector with the content of the (main) diagonal
403  vnl_vector<T> get_diagonal() const;
404 
405  //: Flatten row-major (C-style)
406  vnl_vector<T> flatten_row_major() const;
407 
408  //: Flatten column-major (Fortran-style)
409  vnl_vector<T> flatten_column_major() const;
410 
411  // ==== mutators ====
412 
413  //: Sets this matrix to an identity matrix, then returns "*this".
414  // Returning "*this" allows e.g. passing an identity matrix as argument to
415  // a function f, without having to name the constructed matrix:
416  // \code
417  // f(vnl_matrix<double>(5,5).set_identity());
418  // \endcode
419  // Returning "*this" also allows "chaining" two or more operations:
420  // e.g., to set a 3x3 matrix to [3 0 0][0 2 0][0 0 1], one could say
421  // \code
422  // M.set_identity().scale_row(0,3).scale_column(1,2);
423  // \endcode
424  // If the matrix is not square, anyhow set main diagonal to 1, the rest to 0.
425  vnl_matrix& set_identity();
426 
427  //: Transposes this matrix efficiently, and returns it.
428  // Returning "*this" allows "chaining" two or more operations:
429  // e.g., to fill a square matrix column-wise, fill it rowwise then transpose:
430  // \code
431  // M.copy_in(array).inplace_transpose();
432  // \endcode
433  vnl_matrix& inplace_transpose();
434 
435  //: Reverses the order of rows, and returns "*this".
436  // Returning "*this" allows "chaining" two or more operations:
437  // e.g., to flip both up-down and left-right, one could just say
438  // \code
439  // M.flipud().fliplr();
440  // \endcode
441  vnl_matrix& flipud();
442 
443  //: Reverses the order of columns, and returns "*this".
444  // Returning "*this" allows "chaining" two or more operations:
445  // e.g., to flip both up-down and left-right, one could just say
446  // \code
447  // M.flipud().fliplr();
448  // \endcode
449  vnl_matrix& fliplr();
450 
451  //: Normalizes each row so it is a unit vector, and returns "*this".
452  // Zero rows are not modified
453  // Returning "*this" allows "chaining" two or more operations:
454  // e.g., to set a matrix to a row-normalized all-elements-equal matrix, say
455  // \code
456  // M.fill(1).normalize_rows();
457  // \endcode
458  // Returning "*this" also allows passing such a matrix as argument
459  // to a function f, without having to name the constructed matrix:
460  // \code
461  // f(vnl_matrix<double>(5,5,1.0).normalize_rows());
462  // \endcode
463  vnl_matrix& normalize_rows();
464 
465  //: Normalizes each column so it is a unit vector, and returns "*this".
466  // Zero columns are not modified
467  // Returning "*this" allows "chaining" two or more operations:
468  // e.g., to set a matrix to a column-normalized all-elements-equal matrix, say
469  // \code
470  // M.fill(1).normalize_columns();
471  // \endcode
472  // Returning "*this" also allows passing such a matrix as argument
473  // to a function f, without having to name the constructed matrix:
474  // \code
475  // f(vnl_matrix<double>(5,5,1.0).normalize_columns());
476  // \endcode
477  vnl_matrix& normalize_columns();
478 
479  //: Scales elements in given row by a factor T, and returns "*this".
480  // Returning "*this" allows "chaining" two or more operations:
481  // e.g., to set a 3x3 matrix to [3 0 0][0 2 0][0 0 1], one could say
482  // \code
483  // M.set_identity().scale_row(0,3).scale_column(1,2);
484  // \endcode
485  vnl_matrix& scale_row(unsigned row, T value);
486 
487  //: Scales elements in given column by a factor T, and returns "*this".
488  // Returning "*this" allows "chaining" two or more operations:
489  // e.g., to set a 3x3 matrix to [3 0 0][0 2 0][0 0 1], one could say
490  // \code
491  // M.set_identity().scale_row(0,3).scale_column(1,2);
492  // \endcode
493  vnl_matrix& scale_column(unsigned col, T value);
494 
495  //: Swap this matrix with that matrix
496  void swap(vnl_matrix<T> & that);
497 
498  //: Type def for norms.
499  typedef typename vnl_c_vector<T>::abs_t abs_t;
500 
501  //: Return sum of absolute values of elements
502  abs_t array_one_norm() const { return vnl_c_vector<T>::one_norm(begin(), size()); }
503 
504  //: Return square root of sum of squared absolute element values
505  abs_t array_two_norm() const { return vnl_c_vector<T>::two_norm(begin(), size()); }
506 
507  //: Return largest absolute element value
508  abs_t array_inf_norm() const { return vnl_c_vector<T>::inf_norm(begin(), size()); }
509 
510  //: Return sum of absolute values of elements
511  abs_t absolute_value_sum() const { return array_one_norm(); }
512 
513  //: Return largest absolute value
514  abs_t absolute_value_max() const { return array_inf_norm(); }
515 
516  // $ || M ||_1 := \max_j \sum_i | M_{ij} | $
517  abs_t operator_one_norm() const;
518 
519  // $ || M ||_\inf := \max_i \sum_j | M_{ij} | $
520  abs_t operator_inf_norm() const;
521 
522  //: Return Frobenius norm of matrix (sqrt of sum of squares of its elements)
523  abs_t frobenius_norm() const { return vnl_c_vector<T>::two_norm(begin(), size()); }
524 
525  //: Return Frobenius norm of matrix (sqrt of sum of squares of its elements)
526  abs_t fro_norm() const { return frobenius_norm(); }
527 
528  //: Return RMS of all elements
529  abs_t rms() const { return vnl_c_vector<T>::rms_norm(begin(), size()); }
530 
531  //: Return minimum value of elements
532  T min_value() const { return vnl_c_vector<T>::min_value(begin(), size()); }
533 
534  //: Return maximum value of elements
535  T max_value() const { return vnl_c_vector<T>::max_value(begin(), size()); }
536 
537  //: Return location of minimum value of elements
538  unsigned arg_min() const { return vnl_c_vector<T>::arg_min(begin(), size()); }
539 
540  //: Return location of maximum value of elements
541  unsigned arg_max() const { return vnl_c_vector<T>::arg_max(begin(), size()); }
542 
543  //: Return mean of all matrix elements
544  T mean() const { return vnl_c_vector<T>::mean(begin(), size()); }
545 
546  // predicates
547 
548  //: Return true iff the size is zero.
549  bool empty() const { return !data || !num_rows || !num_cols; }
550 
551  //: Return true if all elements equal to identity.
552  bool is_identity() const;
553 
554  //: Return true if all elements equal to identity, within given tolerance
555  bool is_identity(double tol) const;
556 
557  //: Return true if all elements equal to zero.
558  bool is_zero() const;
559 
560  //: Return true if all elements equal to zero, within given tolerance
561  bool is_zero(double tol) const;
562 
563  //: Return true if all elements of both matrices are equal, within given tolerance
564  bool is_equal(vnl_matrix<T> const& rhs, double tol) const;
565 
566  //: Return true if finite
567  bool is_finite() const;
568 
569  //: Return true if matrix contains NaNs
570  bool has_nans() const;
571 
572  //: abort if size is not as expected
573  // This function does or tests nothing if NDEBUG is defined
574  void assert_size(unsigned VXL_USED_IN_DEBUG(r), unsigned VXL_USED_IN_DEBUG(c)) const
575  {
576 #ifndef NDEBUG
577  assert_size_internal(r, c);
578 #endif
579  }
580  //: abort if matrix contains any INFs or NANs.
581  // This function does or tests nothing if NDEBUG is defined
582  void assert_finite() const
583  {
584 #ifndef NDEBUG
585  assert_finite_internal();
586 #endif
587  }
588 
589  ////----------------------- Input/Output ----------------------------
590 
591  //: Read a vnl_matrix from an ascii std::istream, automatically determining file size if the input matrix has zero size.
592  static vnl_matrix<T> read(std::istream& s);
593 
594  // : Read a vnl_matrix from an ascii std::istream, automatically determining file size if the input matrix has zero size.
595  bool read_ascii(std::istream& s);
596 
597  //--------------------------------------------------------------------------------
598 
599  //: Access the contiguous block storing the elements in the matrix row-wise. O(1).
600  // 1d array, row-major order.
601  T const* data_block() const { return data[0]; }
602 
603  //: Access the contiguous block storing the elements in the matrix row-wise. O(1).
604  // 1d array, row-major order.
605  T * data_block() { return data[0]; }
606 
607  //: Access the 2D array, so that elements can be accessed with array[row][col] directly.
608  // 2d array, [row][column].
609  T const* const* data_array() const { return data; }
610 
611  //: Access the 2D array, so that elements can be accessed with array[row][col] directly.
612  // 2d array, [row][column].
613  T * * data_array() { return data; }
614 
615  typedef T element_type;
616 
617  //: Iterators
618  typedef T *iterator;
619  //: Iterator pointing to start of data
620  iterator begin() { return data?data[0]:nullptr; }
621  //: Iterator pointing to element beyond end of data
622  iterator end() { return data?data[0]+num_rows*num_cols:nullptr; }
623 
624  //: Const iterators
625  typedef T const *const_iterator;
626  //: Iterator pointing to start of data
627  const_iterator begin() const { return data?data[0]:nullptr; }
628  //: Iterator pointing to element beyond end of data
629  const_iterator end() const { return data?data[0]+num_rows*num_cols:nullptr; }
630 
631  //: Return a reference to this.
632  // Useful in code which would prefer not to know if its argument
633  // is a matrix, matrix_ref or a matrix_fixed. Note that it doesn't
634  // return a matrix_ref, so it's only useful in templates or macros.
635  vnl_matrix<T> const& as_ref() const { return *this; }
636 
637  //: Return a reference to this.
638  vnl_matrix<T>& as_ref() { return *this; }
639 
640  //--------------------------------------------------------------------------------
641 
642  //: Return true if *this == rhs
643  bool operator_eq(vnl_matrix<T> const & rhs) const;
644 
645  //: Equality operator
646  bool operator==(vnl_matrix<T> const &that) const { return this->operator_eq(that); }
647 
648  //: Inequality operator
649  bool operator!=(vnl_matrix<T> const &that) const { return !this->operator_eq(that); }
650 
651  //: Print matrix to os in some hopefully sensible format
652  void print(std::ostream& os) const;
653 
654  //: Make the matrix as if it had been default-constructed.
655  void clear();
656 
657  //: Resize to r rows by c columns. Old data lost.
658  // Returns true if size changed.
659  bool set_size(unsigned r, unsigned c);
660 
661 //--------------------------------------------------------------------------------
662 
663  protected:
664  unsigned num_rows; // Number of rows
665  unsigned num_cols; // Number of columns
666  T** data; // Pointer to the vnl_matrix
667 
668  void assert_size_internal(unsigned r, unsigned c) const;
669  void assert_finite_internal() const;
670 
671  //: Delete data
672  void destroy();
673 };
674 
675 
676 // Definitions of inline functions.
677 
678 
679 //: Returns the value of the element at specified row and column. O(1).
680 // Checks for valid range of indices.
681 
682 template<class T>
683 inline T vnl_matrix<T>
684 ::get(unsigned r, unsigned c) const
685 {
686 #if VNL_CONFIG_CHECK_BOUNDS
687  if (r >= this->num_rows) // If invalid size specified
688  vnl_error_matrix_row_index("get", r); // Raise exception
689  if (c >= this->num_cols) // If invalid size specified
690  vnl_error_matrix_col_index("get", c); // Raise exception
691 #endif
692  return this->data[r][c];
693 }
694 
695 //: Puts value into element at specified row and column. O(1).
696 // Checks for valid range of indices.
697 
698 template<class T>
699 inline void vnl_matrix<T>
700 ::put(unsigned r, unsigned c, T const& v)
701 {
702 #if VNL_CONFIG_CHECK_BOUNDS
703  if (r >= this->num_rows) // If invalid size specified
704  vnl_error_matrix_row_index("put", r); // Raise exception
705  if (c >= this->num_cols) // If invalid size specified
706  vnl_error_matrix_col_index("put", c); // Raise exception
707 #endif
708  this->data[r][c] = v; // Assign data value
709 }
710 
711 
712 // non-member arithmetical operators.
713 
714 //:
715 // \relatesalso vnl_matrix
716 template<class T>
717 inline vnl_matrix<T> operator*(T const& value, vnl_matrix<T> const& m)
718 {
719  return vnl_matrix<T>(m, value, vnl_tag_mul());
720 }
721 
722 //:
723 // \relatesalso vnl_matrix
724 template<class T>
725 inline vnl_matrix<T> operator+(T const& value, vnl_matrix<T> const& m)
726 {
727  return vnl_matrix<T>(m, value, vnl_tag_add());
728 }
729 
730 //: Swap two matrices
731 // \relatesalso vnl_matrix
732 template<class T>
733 inline void swap(vnl_matrix<T> &A, vnl_matrix<T> &B) { A.swap(B); }
734 
735 
736 #endif // vnl_matrix_h_
vnl_matrix< T > & operator=(T const &v)
Set all elements to value v.
Definition: vnl_matrix.h:274
vnl_c_vector< T >::abs_t abs_t
Type def for norms.
Definition: vnl_matrix.h:499
vnl_vector_fixed< T, n > element_quotient(const vnl_vector_fixed< T, n > &a, const vnl_vector_fixed< T, n > &b)
unsigned int cols() const
Return the number of columns.
Definition: vnl_matrix.h:183
vnl_matrix()
Default constructor creates an empty matrix of size 0,0.
Definition: vnl_matrix.h:117
abs_t absolute_value_max() const
Return largest absolute value.
Definition: vnl_matrix.h:514
void assert_finite() const
abort if matrix contains any INFs or NANs.
Definition: vnl_matrix.h:582
const_iterator begin() const
Iterator pointing to start of data.
Definition: vnl_matrix.h:627
vnl_bignum operator+(vnl_bignum const &r1, long r2)
Returns the sum of two bignum numbers.
Definition: vnl_bignum.h:279
abs_t absolute_value_sum() const
Return sum of absolute values of elements.
Definition: vnl_matrix.h:511
abs_t rms() const
Return RMS of all elements.
Definition: vnl_matrix.h:529
vnl_matrix< T > operator/(T const &v) const
Scalar division of lhs matrix by rhs and return result in new matrix.
Definition: vnl_matrix.h:317
iterator end()
Iterator pointing to element beyond end of data.
Definition: vnl_matrix.h:622
const_iterator end() const
Iterator pointing to element beyond end of data.
Definition: vnl_matrix.h:629
vnl_matrix(vnl_matrix< T > &that, vnl_tag_grab)
Definition: vnl_matrix.h:163
abs_t array_one_norm() const
Return sum of absolute values of elements.
Definition: vnl_matrix.h:502
static unsigned arg_min(T const *, unsigned)
Returns location of min value of the vector.
vnl_matrix< T > & as_ref()
Return a reference to this.
Definition: vnl_matrix.h:638
abs_t fro_norm() const
Return Frobenius norm of matrix (sqrt of sum of squares of its elements).
Definition: vnl_matrix.h:526
T * operator[](unsigned r)
return pointer to given row.
Definition: vnl_matrix.h:197
#define m
Definition: vnl_vector.h:43
vnl_matrix< T > operator-(T const &v) const
Subtract rhs from each element of lhs matrix and return result in new matrix.
Definition: vnl_matrix.h:311
vnl_vector_fixed< T, n > element_product(const vnl_vector_fixed< T, n > &a, const vnl_vector_fixed< T, n > &b)
static abs_t rms_norm(T const *p, unsigned n)
rms_norm : sqrt of mean sum of squared abs values.
Definition: vnl_c_vector.h:136
T const * operator[](unsigned r) const
return pointer to given row.
Definition: vnl_matrix.h:201
iterator begin()
Iterator pointing to start of data.
Definition: vnl_matrix.h:620
void vnl_error_matrix_row_index(char const *fcn, int r)
Raise exception for invalid row index.
Definition: vnl_error.cxx:51
void vnl_error_matrix_col_index(char const *fcn, int c)
Raise exception for invalid col index.
Definition: vnl_error.cxx:61
abs_t frobenius_norm() const
Return Frobenius norm of matrix (sqrt of sum of squares of its elements).
Definition: vnl_matrix.h:523
static abs_t one_norm(T const *p, unsigned n)
one_norm : sum of abs values.
Definition: vnl_c_vector.h:120
static abs_t two_norm(T const *p, unsigned n)
two_norm : sqrt of sum of squared abs values.
Definition: vnl_c_vector.h:124
enum VNL_EXPORT vnl_matrix_type
Definition: vnl_matrix.h:80
abs_t array_inf_norm() const
Return largest absolute element value.
Definition: vnl_matrix.h:508
std::ostream & operator<<(std::ostream &s, vnl_decnum const &r)
decimal output.
Definition: vnl_decnum.h:393
unsigned arg_min() const
Return location of minimum value of elements.
Definition: vnl_matrix.h:538
vnl_matrix & set(T const *d)
Fills (laminates) this matrix with the given data, then returns it.
Definition: vnl_matrix.h:265
T get(unsigned r, unsigned c) const
get element with boundary checks if error checking is on.
Definition: vnl_matrix.h:684
#define v
Definition: vnl_vector.h:42
T * data_block()
Access the contiguous block storing the elements in the matrix row-wise. O(1).
Definition: vnl_matrix.h:605
abs_t array_two_norm() const
Return square root of sum of squared absolute element values.
Definition: vnl_matrix.h:505
T ** data_array()
Access the 2D array, so that elements can be accessed with array[row][col] directly.
Definition: vnl_matrix.h:613
vnl_matrix< T > const & as_ref() const
Return a reference to this.
Definition: vnl_matrix.h:635
static unsigned arg_max(T const *, unsigned)
Returns location of max value of the vector.
static T min_value(T const *, unsigned)
Returns min value of the vector.
unsigned num_rows
Definition: vnl_matrix.h:664
An ordinary mathematical matrix.
Definition: vnl_adjugate.h:22
T max_value() const
Return maximum value of elements.
Definition: vnl_matrix.h:535
static T mean(T const *p, unsigned n)
Definition: vnl_c_vector.h:108
T mean() const
Return mean of all matrix elements.
Definition: vnl_matrix.h:544
bool operator==(vnl_matrix< T > const &that) const
Equality operator.
Definition: vnl_matrix.h:646
VNL_EXPORT T inner_product(m const &, m const &)
VNL_EXPORT m operator-(T const &, m const &)
vnl_matrix< T > operator+(vnl_matrix< T > const &rhs) const
Matrix add rhs to lhs matrix and return result in new matrix.
Definition: vnl_matrix.h:320
void assert_size(unsigned VXL_USED_IN_DEBUG(r), unsigned VXL_USED_IN_DEBUG(c)) const
abort if size is not as expected.
Definition: vnl_matrix.h:574
unsigned num_cols
Definition: vnl_matrix.h:665
T * iterator
Iterators.
Definition: vnl_matrix.h:618
T const *const * data_array() const
Access the 2D array, so that elements can be accessed with array[row][col] directly.
Definition: vnl_matrix.h:609
T dot_product(const vnl_vector_fixed< T, n > &a, const vnl_vector_fixed< T, n > &b)
void swap(vnl_matrix< T > &that)
Swap this matrix with that matrix.
vnl_numeric_traits< T >::abs_t abs_t
Definition: vnl_c_vector.h:42
bool empty() const
Return true iff the size is zero.
Definition: vnl_matrix.h:549
void swap(vnl_matrix< T > &A, vnl_matrix< T > &B)
Swap two matrices.
Definition: vnl_matrix.h:733
Mathematical vector class, templated by type of element.
Definition: vnl_fwd.h:16
T const * data_block() const
Access the contiguous block storing the elements in the matrix row-wise. O(1).
Definition: vnl_matrix.h:601
T const * const_iterator
Const iterators.
Definition: vnl_matrix.h:625
vnl_matrix_null
Definition: vnl_matrix.h:82
unsigned int size() const
Return the total number of elements stored by the matrix.
Definition: vnl_matrix.h:176
bool operator!=(vnl_matrix< T > const &that) const
Inequality operator.
Definition: vnl_matrix.h:649
unsigned int rows() const
Return the number of rows.
Definition: vnl_matrix.h:179
unsigned arg_max() const
Return location of maximum value of elements.
Definition: vnl_matrix.h:541
vnl_matrix< T > operator-(vnl_matrix< T > const &rhs) const
Matrix subtract rhs from lhs and return result in new matrix.
Definition: vnl_matrix.h:322
T min_value() const
Return minimum value of elements.
Definition: vnl_matrix.h:532
VNL_EXPORT std::istream & operator>>(std::istream &s, vnl_decnum &r)
decimal input.
Definition: vnl_decnum.cxx:411
vnl_bignum operator-(vnl_bignum const &r1, vnl_bignum const &r2)
Returns the difference of two bignum numbers.
Definition: vnl_bignum.h:290
static T max_value(T const *, unsigned)
Returns max value of the vector.
void swap(vnl_matrix< T > &A, vnl_matrix< T > &B)
Swap two matrices.
Definition: vnl_matrix.h:733
VNL_EXPORT m operator *(T const &, m const &)
VNL_EXPORT T cos_angle(m const &, m const &)
vnl_matrix< T > operator+(T const &v) const
Add rhs to each element of lhs matrix and return result in new matrix.
Definition: vnl_matrix.h:308
vnl_bignum operator *(vnl_bignum const &r1, vnl_bignum const &r2)
Returns the product of two bignum numbers.
Definition: vnl_bignum.h:302
unsigned int columns() const
Return the number of columns.
Definition: vnl_matrix.h:187
Math on blocks of memory.
static abs_t inf_norm(T const *p, unsigned n)
inf_norm : max of abs values.
Definition: vnl_c_vector.h:128
void put(unsigned r, unsigned c, T const &)
set element with boundary checks if error checking is on.
Definition: vnl_matrix.h:700