00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028 #ifndef mrpt_math_matrix_ops_H
00029 #define mrpt_math_matrix_ops_H
00030
00031 #include <mrpt/math/math_frwds.h>
00032
00033 #include <mrpt/math/CMatrix.h>
00034 #include <mrpt/math/CMatrixD.h>
00035 #include <mrpt/utils/CStream.h>
00036
00037 #include <mrpt/math/CMatrixTemplateNumeric.h>
00038 #include <mrpt/math/CMatrixFixedNumeric.h>
00039 #include <mrpt/math/CVectorTemplate.h>
00040
00041 #include <mrpt/math/ops_containers.h>
00042 #include <mrpt/math/ops_matrices_eigen.h>
00043 #include <mrpt/math/matrices_metaprogramming.h>
00044
00045 #include <mrpt/utils/metaprogramming.h>
00046
00047
00048
00049
00050
00051
00052
00053 namespace mrpt
00054 {
00055 namespace math
00056 {
00057
00058 template <size_t NROWS,size_t NCOLS>
00059 mrpt::utils::CStream &operator>>(mrpt::utils::CStream &in, CMatrixFixedNumeric<float,NROWS,NCOLS> & M) {
00060 CMatrix aux;
00061 in.ReadObject(&aux);
00062 ASSERTMSG_(M.size()==aux.size(), format("Size mismatch: deserialized is %ux%u, expected is %ux%u",(unsigned)aux.getRowCount(),(unsigned)aux.getColCount(),(unsigned)NROWS,(unsigned)NCOLS))
00063 M = aux;
00064 return in;
00065 }
00066
00067 template <size_t NROWS,size_t NCOLS>
00068 mrpt::utils::CStream &operator>>(mrpt::utils::CStream &in, CMatrixFixedNumeric<double,NROWS,NCOLS> & M) {
00069 CMatrixD aux;
00070 in.ReadObject(&aux);
00071 ASSERTMSG_(M.size()==aux.size(), format("Size mismatch: deserialized is %ux%u, expected is %ux%u",(unsigned)aux.getRowCount(),(unsigned)aux.getColCount(),(unsigned)NROWS,(unsigned)NCOLS))
00072 M = aux;
00073 return in;
00074 }
00075
00076
00077 template <size_t NROWS,size_t NCOLS>
00078 mrpt::utils::CStream &operator<<(mrpt::utils::CStream &out,const CMatrixFixedNumeric<float,NROWS,NCOLS> & M) {
00079 CMatrix aux = CMatrixFloat(M);
00080 out.WriteObject(&aux);
00081 return out;
00082 }
00083
00084 template <size_t NROWS,size_t NCOLS>
00085 mrpt::utils::CStream &operator<<(mrpt::utils::CStream &out,const CMatrixFixedNumeric<double,NROWS,NCOLS> & M) {
00086 CMatrixD aux = CMatrixDouble(M);
00087 out.WriteObject(&aux);
00088 return out;
00089 }
00090
00091
00092 template <class T,size_t NROWS, size_t NCOLS>
00093 bool operator == (const CMatrixFixedNumeric<T,NROWS,NCOLS>& M1, const CMatrixFixedNumeric<T,NROWS,NCOLS>& M2)
00094 {
00095 for (size_t i=0; i < NROWS; i++)
00096 for (size_t j=0; j < NCOLS; j++)
00097 if (M1.get_unsafe(i,j)!=M2.get_unsafe(i,j))
00098 return false;
00099 return true;
00100 }
00101
00102
00103
00104
00105 template <class MATRIX>
00106 RET_TYPE_ASSERT_MRPTMATRIX(MATRIX, std::ostream)&
00107 operator << (std::ostream& ostrm, const MATRIX& m)
00108 {
00109 ostrm << std::setprecision(4);
00110 for (size_t i=0; i < m.getRowCount(); i++)
00111 {
00112 for (size_t j=0; j < m.getColCount(); j++)
00113 ostrm << std::setw(13) << m(i,j);
00114 ostrm << std::endl;
00115 }
00116 return ostrm;
00117 }
00118
00119
00120
00121
00122
00123 namespace detail
00124 {
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135 template<class MATRIX1,class MATRIX2>
00136 bool chol(const MATRIX1 &in, MATRIX2 &out)
00137 {
00138 typedef typename MATRIX1::value_type T;
00139 const size_t N=in.getRowCount();
00140 if (in.getColCount()!=in.getRowCount()) throw std::logic_error("Error in Cholesky factorization. Matrix is not square");
00141 out.setSize(N,N);
00142 {
00143 T coef=in.get_unsafe(0,0);
00144 if (coef<=0) return false;
00145 else out.get_unsafe(0,0)=(coef=sqrt(coef));
00146 for (size_t j=1;j<N;++j) out.get_unsafe(0,j)=in.get_unsafe(0,j)/coef;
00147 }
00148 T sum;
00149 for (size_t i=1;i<N;++i) {
00150 out.set_unsafe(i,0,0);
00151 {
00152 sum=in.get_unsafe(i,i);
00153 for (size_t k=i-1;k<N;--k) sum-=square(out.get_unsafe(k,i));
00154 if (sum<=0) return false;
00155 else out.get_unsafe(i,i)=sqrt(sum);
00156 }
00157 for (size_t j=i+1;j<N;++j) {
00158 sum=in.get_unsafe(i,j);
00159 for (size_t k=i-1;k<N;--k) sum-=out.get_unsafe(k,i)*out.get_unsafe(k,j);
00160 out.get_unsafe(i,j)=sum/out.get_unsafe(i,i);
00161 out.get_unsafe(j,i)=0;
00162 }
00163 }
00164 return true;
00165 }
00166
00167
00168
00169
00170
00171
00172
00173
00174
00175 template <class MAT>
00176 void saveMatrixToTextFile(
00177 const MAT &theMatrix,
00178 const std::string &file,
00179 TMatrixTextFileFormat fileFormat,
00180 bool appendMRPTHeader,
00181 const std::string &userHeader
00182 )
00183 {
00184 using namespace mrpt::system;
00185
00186 MRPT_START;
00187
00188 FILE *f=os::fopen(file.c_str(),"wt");
00189 if (!f)
00190 THROW_EXCEPTION_CUSTOM_MSG1("saveToTextFile: Error opening file '%s' for writing a matrix as text.", file.c_str());
00191
00192 if (!userHeader.empty())
00193 fprintf(f,"%s",userHeader.c_str() );
00194
00195 if (appendMRPTHeader)
00196 fprintf(f,"%% File generated with MRPT %s at %s\n%%-----------------------------------------------------------------\n",
00197 mrpt::system::MRPT_getVersion().c_str(),
00198 mrpt::system::dateTimeLocalToString( mrpt::system::now() ).c_str() );
00199
00200 for (size_t i=0; i < theMatrix.getRowCount(); i++)
00201 {
00202 for (size_t j=0; j < theMatrix.getColCount(); j++)
00203 {
00204 switch(fileFormat)
00205 {
00206 case MATRIX_FORMAT_ENG: os::fprintf(f,"%.16e",static_cast<double>(theMatrix(i,j))); break;
00207 case MATRIX_FORMAT_FIXED: os::fprintf(f,"%.16f",static_cast<double>(theMatrix(i,j))); break;
00208 case MATRIX_FORMAT_INT: os::fprintf(f,"%i",static_cast<int>(theMatrix(i,j))); break;
00209 default:
00210 THROW_EXCEPTION("Unsupported value for the parameter 'fileFormat'!");
00211 };
00212
00213 if (j<(theMatrix.getColCount()-1)) os::fprintf(f," ");
00214 }
00215 os::fprintf(f,"\n");
00216 }
00217 os::fclose(f);
00218 MRPT_END;
00219 }
00220
00221
00222
00223
00224 template <class MATRIX>
00225 std::string matrix_inMatlabFormat(const MATRIX &m,const size_t decimal_digits)
00226 {
00227 std::stringstream s;
00228 s << "[" << std::scientific;
00229 s.precision(decimal_digits);
00230 for (size_t i=0;i<m.getRowCount();i++)
00231 {
00232 for (size_t j=0;j<m.getColCount();j++)
00233 s << m.get_unsafe(i,j) << " ";
00234 if (i<m.getRowCount()-1) s << ";";
00235 }
00236 s << "]";
00237 return s.str();
00238 }
00239
00240
00241
00242
00243 template<class MATRIX1>
00244 typename MATRIX1::value_type trace(const MATRIX1 &m)
00245 {
00246 if (!m.IsSquare()) throw std::logic_error("Error in trace: matrix is not square");
00247 const size_t N = size(m,1);
00248 typename MATRIX1::value_type ret=0;
00249 for (size_t i=0;i<N;i++)
00250 ret+=m.get_unsafe(i,i);
00251 return ret;
00252 }
00253
00254
00255 template<class MATRIX1, class OTHERVECTOR1,class OTHERVECTOR2>
00256 void multiply_Ab(const MATRIX1 &m, const OTHERVECTOR1 &vIn,OTHERVECTOR2 &vOut,bool accumToOutput ) {
00257 MRPT_START
00258 size_t N=m.getRowCount();
00259 size_t M=m.getColCount();
00260 ASSERT_(vIn.size()==M)
00261 vOut.resize(N);
00262 if (!accumToOutput) for (size_t i=0;i<N;++i) vOut[i]=typename OTHERVECTOR2::value_type(0);
00263 for (size_t i=0;i<N;++i) {
00264 typename MATRIX1::value_type &accum=vOut[i];
00265 for (size_t j=0;j<M;++j) accum+=m.get_unsafe(i,j)*vIn[j];
00266 }
00267 MRPT_END
00268 }
00269
00270
00271 template<class MATRIX1, class OTHERVECTOR1,class OTHERVECTOR2>
00272 void multiply_Atb(const MATRIX1 &m, const OTHERVECTOR1 &vIn,OTHERVECTOR2 &vOut,bool accumToOutput ) {
00273 MRPT_START
00274 size_t N=m.getColCount();
00275 size_t M=m.getRowCount();
00276 ASSERT_(vIn.size()==M)
00277 vOut.resize(N);
00278 if (!accumToOutput) for (size_t i=0;i<N;++i) vOut[i]=typename OTHERVECTOR2::value_type(0);
00279 for (size_t i=0;i<N;++i) {
00280 typename MATRIX1::value_type &accum=vOut[i];
00281 for (size_t j=0;j<M;++j) accum+=m.get_unsafe(j,i)*vIn[j];
00282 }
00283 MRPT_END
00284 }
00285
00286
00287 template <class MATRIX1,class MATRIX2>
00288 void multiply_AAt( const MATRIX1& m1, MATRIX2& RESULT )
00289 {
00290 typedef typename MATRIX2::value_type T;
00291 const size_t M1R = m1.getRowCount();
00292 const size_t M1C = m1.getColCount();
00293 RESULT.setSize(M1R,M1R);
00294
00295
00296 if ((void*)&m1==(void*)&RESULT)
00297 {
00298
00299 std::vector<T> temp(M1R*M1R);
00300
00301 T *ptr = &temp[0];
00302 size_t i;
00303 for (i=0; i < M1R; i++)
00304 {
00305 for (size_t j=i; j < M1R; j++)
00306 {
00307 T accum = 0;
00308 for (size_t k=0; k < M1C; k++)
00309 accum += m1.get_unsafe(i,k) * m1.get_unsafe(j,k);
00310 *(ptr++) = accum;
00311 }
00312 }
00313
00314 ptr = &temp[0];
00315 for (i=0; i < M1R; i++)
00316 for (size_t j=i; j < M1R; j++)
00317 RESULT.get_unsafe(i,j) = RESULT.get_unsafe(j,i) = *(ptr++);
00318 }
00319 else
00320 {
00321
00322 for (size_t i=0; i < M1R; i++)
00323 for (size_t j=i; j < M1R; j++)
00324 {
00325 T accum = 0;
00326 for (size_t k=0; k < M1C; k++)
00327 accum += m1.get_unsafe(i,k) * m1.get_unsafe(j,k);
00328 RESULT.get_unsafe(i,j) = RESULT.get_unsafe(j,i) = accum;
00329 }
00330 }
00331 }
00332
00333
00334 template <class MATRIX1,class MATRIX2>
00335 void multiply_AtA( const MATRIX1& m1, MATRIX2& RESULT )
00336 {
00337 typedef typename MATRIX2::value_type T;
00338 const size_t M1R = m1.getRowCount();
00339 const size_t M1C = m1.getColCount();
00340 RESULT.setSize(M1C,M1C);
00341
00342
00343 if ((void*)&m1==(void*)&RESULT)
00344 {
00345
00346 std::vector<T> temp(M1C*M1C);
00347
00348 T *ptr = &temp[0];
00349 size_t i;
00350 for (i=0; i < M1C; i++)
00351 {
00352 for (size_t j=i; j < M1C; j++)
00353 {
00354 T accum = 0;
00355 for (size_t k=0; k < M1R; k++)
00356 accum += m1.get_unsafe(i,k) * m1.get_unsafe(j,k);
00357 *(ptr++) = accum;
00358 }
00359 }
00360
00361 ptr = &temp[0];
00362 for (i=0; i < M1C; i++)
00363 for (size_t j=i; j < M1C; j++)
00364 RESULT.get_unsafe(i,j) = RESULT.get_unsafe(j,i) = *(ptr++);
00365 }
00366 else
00367 {
00368
00369 for (size_t i=0; i < M1C; i++)
00370 {
00371 for (size_t j=i; j < M1C; j++)
00372 {
00373 T accum = 0;
00374 for (size_t k=0; k < M1R; k++)
00375 accum += m1.get_unsafe(k,i) * m1.get_unsafe(k,j);
00376 RESULT.get_unsafe(i,j) = RESULT.get_unsafe(j,i) = accum;
00377 }
00378 }
00379 }
00380 }
00381
00382
00383 template <class MATRIX1,class MATRIX2,class MATRIXRES>
00384 void multiply_AB(const MATRIX1& m1,const MATRIX2& m2, MATRIXRES& RESULT )
00385 {
00386 MRPT_START
00387
00388 typedef typename MATRIXRES::value_type T;
00389
00390 const size_t NROWS = m1.getRowCount();
00391 const size_t NCOLS = m2.getColCount();
00392 const size_t M1C = m1.getColCount();
00393 ASSERTMSG_(M1C==m2.getRowCount(),format("Invalid matrix sizes in multiplication: %ux%u * %ux%u",(unsigned int)NROWS,(unsigned int)M1C,(unsigned int)m2.getRowCount(),(unsigned int)NCOLS ));
00394
00395 RESULT.setSize(NROWS,NCOLS);
00396
00397
00398 if ( (void*)(&m1)==(void*)(&RESULT) || (void*)(&m2)==(void*)&RESULT)
00399 {
00400
00401 std::vector<T> temp(NROWS*NCOLS);
00402 size_t out_idx = 0;
00403 for (size_t i=0; i < NROWS; i++)
00404 {
00405 for (size_t j=0; j < NCOLS; j++)
00406 {
00407 T accum = 0;
00408 for (size_t k=0; k < M1C; k++)
00409 accum += m1.get_unsafe(i,k) * m2.get_unsafe(k,j);
00410 temp[out_idx++] = accum;
00411 }
00412 }
00413
00414
00415 T* ptr = &temp[0];
00416 for (size_t i=0; i < NROWS; i++)
00417 for (size_t j=0; j < NCOLS; j++)
00418 RESULT.get_unsafe(i,j)= *(ptr++);
00419 }
00420 else
00421 {
00422
00423 for (size_t i=0; i < NROWS; i++)
00424 {
00425 for (size_t j=0; j < NCOLS; j++)
00426 {
00427 T accum = 0;
00428 for (size_t k=0; k < M1C; k++)
00429 accum += m1.get_unsafe(i,k) * m2.get_unsafe(k,j);
00430 RESULT.get_unsafe(i,j)=accum;
00431 }
00432 }
00433 }
00434
00435 MRPT_END
00436 }
00437
00438 template<typename MAT_IN_1,typename MAT_IN_2,typename MAT_OUT> void multiply_AtB(const MAT_IN_1 &A,const MAT_IN_2 &B,MAT_OUT &C) {
00439 size_t sA=A.getColCount(),sB=B.getColCount();
00440 size_t N=A.getRowCount();
00441 ASSERTMSG_(N==B.getRowCount(),format("Invalid matrix sizes in multiplication: %ux%u * %ux%u",(unsigned int)sA,(unsigned int)N,(unsigned int)B.getRowCount(),(unsigned int)sB));
00442 if (((void *)&A==(void *)&C)||((void *)&B==(void *)&C)) {
00443
00444 MAT_TYPE_PRODUCT_AtB_OF(MAT_IN_1,MAT_IN_2) tmpMat;
00445 for (size_t i=0;i<sA;++i) for (size_t j=0;j<sB;++j) {
00446
00447
00448
00449
00450
00451 tmpMat.set_unsafe(i,j,A.get_unsafe(0,i)*B.get_unsafe(0,j));
00452 for (size_t k=1;k<N;++k) tmpMat.get_unsafe(i,j)+=A.get_unsafe(k,i)*B.get_unsafe(k,j);
00453 }
00454 C.setSize(sA,sB);
00455 for (size_t i=0;i<sA;++i) for (size_t j=0;j<sB;++j) C.set_unsafe(i,j,tmpMat.get_unsafe(i,j));
00456 } else {
00457 C.setSize(sA,sB);
00458 for (size_t i=0;i<sA;++i) for (size_t j=0;j<sB;++j) {
00459
00460 C.set_unsafe(i,j,A.get_unsafe(0,i)*B.get_unsafe(0,j));
00461 for (size_t k=1;k<N;++k) C.get_unsafe(i,j)+=A.get_unsafe(k,i)*B.get_unsafe(k,j);
00462 }
00463 }
00464 }
00465
00466
00467
00468 template <typename MAT_H, typename MAT_C, typename MAT_R>
00469 void multiply_HCHt(
00470 const MAT_H &H,
00471 const MAT_C &C,
00472 MAT_R &R,
00473 bool accumResultInOutput,
00474 bool allow_submatrix_mult)
00475 {
00476 MRPT_START
00477
00478 ASSERTMSG_( (void*)&C != (void*)&H, "C and H must be different matrices." )
00479 ASSERTMSG_( (void*)&R != (void*)&H, "R and H must be different matrices." )
00480 ASSERTMSG_( (void*)&C != (void*)&R, "C and R must be different matrices.")
00481 ASSERT_(C.IsSquare())
00482
00483 if (allow_submatrix_mult)
00484 ASSERT_(C.getRowCount()>=H.getColCount())
00485 else ASSERT_(C.getRowCount()==H.getColCount())
00486
00487 const size_t N=H.getRowCount();
00488 const size_t M=H.getColCount();
00489
00490 R.setSize(N,N);
00491
00492
00493 MAT_TYPE_PRODUCT_OF(MAT_H,MAT_C) R_;
00494 R_.setSize(N,M);
00495
00496
00497 for (size_t i=0;i<N;i++)
00498 for (size_t j=0;j<M;j++)
00499 {
00500 typename MAT_H::value_type sumAccum = 0;
00501 for (size_t l=0;l<M;l++)
00502 sumAccum += H.get_unsafe(i,l) * C.get_unsafe(l,j);
00503 R_.get_unsafe(i,j) = sumAccum;
00504 }
00505
00506
00507 for (size_t i=0;i<N;i++)
00508 for (size_t j=i;j<N;j++)
00509 {
00510 typename MAT_H::value_type sumAccum = accumResultInOutput ? R.get_unsafe(i,j) : 0;
00511 for (size_t l=0;l<M;l++)
00512 sumAccum += R_.get_unsafe(i,l) * H.get_unsafe(j,l);
00513 R.get_unsafe(i,j) = R.get_unsafe(j,i) = sumAccum;
00514 }
00515 MRPT_END
00516 }
00517
00518
00519 template <typename VECTOR_H, typename MAT_C>
00520 typename MAT_C::value_type
00521 multiply_HCHt_scalar(const VECTOR_H &H, const MAT_C &C)
00522 {
00523 MRPT_START
00524 ASSERT_( C.IsSquare() )
00525
00526 const size_t M = H.size();
00527
00528
00529 ASSERT_( size(C,1)==M );
00530
00531 typename VECTOR_H::value_type sumAccum = 0;
00532 typename VECTOR_H::const_iterator itL=H.begin();
00533 for (size_t l=0;l<M; ++l, ++itL)
00534 {
00535 typename VECTOR_H::value_type sumAccumInner = 0;
00536 typename VECTOR_H::const_iterator it;
00537 size_t k;
00538 for (k=0,it=H.begin();it!=H.end();++it,++k)
00539 sumAccumInner += *it * C.get_unsafe(k,l);
00540 sumAccum += sumAccumInner * (*itL);
00541 }
00542 return sumAccum;
00543 MRPT_END
00544 }
00545
00546
00547 template <typename MAT_H, typename MAT_C, typename MAT_R>
00548 void multiply_HtCH(
00549 const MAT_H &H,
00550 const MAT_C &C,
00551 MAT_R &R,
00552 bool accumResultInOutput,
00553 bool allow_submatrix_mult)
00554 {
00555 MRPT_START
00556
00557 ASSERTMSG_( (void*)&C != (void*)&H, "C and H must be different matrices." )
00558 ASSERTMSG_( (void*)&R != (void*)&H, "R and H must be different matrices." )
00559 ASSERTMSG_( (void*)&C != (void*)&R, "C and R must be different matrices.")
00560 ASSERT_(C.IsSquare())
00561
00562 if (allow_submatrix_mult)
00563 ASSERT_(C.getRowCount()>=H.getRowCount())
00564 else ASSERT_(C.getRowCount()==H.getRowCount())
00565
00566 R.setSize( H.getColCount(), H.getColCount());
00567
00568 MAT_H R_;
00569
00570 const size_t M=H.getRowCount();
00571 const size_t N=H.getColCount();
00572
00573
00574 for (size_t i=0;i<N;i++)
00575 for (size_t j=0;j<M;j++)
00576 {
00577 typename MAT_H::value_type sumAccum = 0;
00578 for (size_t l=0;l<M;l++)
00579 sumAccum += H.get_unsafe(l,i) * C.get_unsafe(l,j);
00580 R_.get_unsafe(i,j) = sumAccum;
00581 }
00582
00583
00584 for (size_t i=0;i<N;i++)
00585 for (size_t j=i;j<N;j++)
00586 {
00587 typename MAT_H::value_type sumAccum = accumResultInOutput ? R.get_unsafe(i,j) : 0;
00588 for (size_t l=0;l<M;l++)
00589 sumAccum += R_.get_unsafe(i,l) * H.get_unsafe(l,j);
00590 R.get_unsafe(i,j) = R.get_unsafe(j,i) = sumAccum;
00591 }
00592 MRPT_END
00593 }
00594
00595
00596
00597
00598
00599 template<typename MAT_IN,typename MAT_OUT> void multiply_AAt_scalar(const MAT_IN &in,typename MAT_IN::value_type scalar,MAT_OUT &out) {
00600 MRPT_START
00601 ASSERTMSG_((void*)&in!=(void*)&out,"The matrices mustn't be the same." )
00602 size_t r=in.getRowCount();
00603 size_t c=in.getColCount();
00604 out.setSize(r,r);
00605 typename MAT_IN::value_type accum=typename MAT_IN::value_type(0);
00606 for (size_t k=0;k<c;++k) accum+=square(in.get_unsafe(0,k));
00607 out.set_unsafe(0,0,accum*scalar);
00608 for (size_t i=1;i<r;++i) {
00609 for (size_t j=0;j<i;++j) {
00610 accum=typename MAT_IN::value_type(0);
00611 for (size_t k=0;k<c;++k) accum+=in.get_unsafe(i,k)*in.get_unsafe(j,k);
00612 accum*=scalar;
00613 out.set_unsafe(i,j,accum);
00614 out.set_unsafe(j,i,accum);
00615 }
00616 accum=typename MAT_IN::value_type(0);
00617 for (size_t k=0;k<c;++k) accum+=square(in.get_unsafe(i,k));
00618 out.set_unsafe(i,i,accum*scalar);
00619 }
00620 MRPT_END
00621 }
00622
00623
00624
00625
00626
00627
00628 template<typename MAT_IN,typename MAT_OUT> void multiply_AtA_scalar(const MAT_IN &in,typename MAT_IN::value_type scalar,MAT_OUT &out) {
00629 MRPT_START
00630 ASSERTMSG_((void*)&in!=(void*)&out,"The matrices mustn't be the same." )
00631 size_t r=in.getRowCount();
00632 size_t c=in.getColCount();
00633 out.setSize(c,c);
00634 typename MAT_IN::value_type accum=typename MAT_IN::value_type(0);
00635 for (size_t k=0;k<c;++k) accum+=square(in.get_unsafe(k,0));
00636 out.set_unsafe(0,0,accum*scalar);
00637 for (size_t i=1;i<r;++i) {
00638 for (size_t j=0;j<i;++j) {
00639 accum=typename MAT_IN::value_type(0);
00640 for (size_t k=0;k<c;++k) accum+=in.get_unsafe(k,i)*in.get_unsafe(k,j);
00641 accum*=scalar;
00642 out.set_unsafe(i,j,accum);
00643 out.set_unsafe(j,i,accum);
00644 }
00645 accum=typename MAT_IN::value_type(0);
00646 for (size_t k=0;k<c;++k) accum+=square(in.get_unsafe(k,i));
00647 out.set_unsafe(i,i,accum*scalar);
00648 }
00649 MRPT_END
00650 }
00651
00652
00653
00654
00655 template <class MAT_X,class MAT_A,class MAT_OUT>
00656 void multiply_subMatrix (
00657 const MAT_X &X,
00658 const MAT_A &A,
00659 MAT_OUT &outResult,
00660 const size_t A_cols_offset,
00661 const size_t A_rows_offset,
00662 const size_t A_col_count)
00663 {
00664 MRPT_START
00665
00666 const size_t N = X.getRowCount();
00667 const size_t M = A_col_count;
00668 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
00669 ASSERT_( A.getColCount() >= A_col_count + A_cols_offset );
00670 ASSERT_( A.getRowCount() >= N + A_rows_offset );
00671 #endif
00672 outResult.setSize(N,M);
00673 for (size_t i=0; i < N; i++)
00674 for (size_t j=0; j < M; j++)
00675 {
00676 typename MAT_OUT::value_type tmp = 0;
00677 for (size_t k=0; k < X.getColCount(); k++)
00678 tmp += X.get_unsafe(i,k) * A.get_unsafe(k+A_rows_offset,j+A_cols_offset);
00679 outResult.get_unsafe(i,j) = tmp;
00680 }
00681 MRPT_END
00682 }
00683
00684
00685 template <class MAT_A,class MAT_B,class MAT_C,class MAT_OUT>
00686 void multiply_ABC(const MAT_A &A, const MAT_B &B, const MAT_C &C, MAT_OUT & RES)
00687 {
00688 const size_t NROWS = A.getRowCount();
00689 const size_t N1 = B.getRowCount();
00690 const size_t N2 = B.getColCount();
00691 const size_t NCOLS = C.getColCount();
00692 ASSERT_( A.getColCount()==B.getRowCount() && B.getColCount()==C.getRowCount() )
00693
00694 RES.zeros();
00695 for (size_t i=0;i<NROWS;i++)
00696 for (size_t l=0;l<N2;l++)
00697 {
00698 typename MAT_OUT::value_type sumAccumInner = 0;
00699 for (size_t k=0;k<N1;k++)
00700 sumAccumInner += A.get_unsafe(i,k) * B.get_unsafe(k,l);
00701 for (size_t j=0;j<NCOLS;j++)
00702 RES.get_unsafe(i,j) += sumAccumInner * C.get_unsafe(l,j);
00703 }
00704 }
00705
00706
00707 template <class MAT_A,class MAT_B,class MAT_C,class MAT_OUT>
00708 void multiply_ABCt(const MAT_A &A, const MAT_B &B, const MAT_C &C, MAT_OUT & RES)
00709 {
00710 const size_t NROWS = A.getRowCount();
00711 const size_t N1 = B.getRowCount();
00712 const size_t N2 = B.getColCount();
00713 const size_t NCOLS = C.getRowCount();
00714 ASSERT_( A.getColCount()==B.getRowCount() && B.getColCount()==C.getColCount() )
00715
00716 RES.zeros();
00717 for (size_t i=0;i<NROWS;i++)
00718 for (size_t l=0;l<N2;l++)
00719 {
00720 typename MAT_OUT::value_type sumAccumInner = 0;
00721 for (size_t k=0;k<N1;k++)
00722 sumAccumInner += A.get_unsafe(i,k) * B.get_unsafe(k,l);
00723 for (size_t j=0;j<NCOLS;j++)
00724 RES.get_unsafe(i,j) += sumAccumInner * C.get_unsafe(j,l);
00725 }
00726 }
00727
00728 template <class MAT_A,class MAT_B,class MAT_OUT>
00729 void multiply_ABt(const MAT_A &m1,const MAT_B &m2, MAT_OUT &out)
00730 {
00731 MRPT_START
00732 typedef typename MAT_OUT::value_type T;
00733 const size_t M1R = m1.getRowCount();
00734 const size_t M1C = m1.getColCount();
00735 const size_t M2C = m2.getRowCount();
00736
00737 ASSERTMSG_(m1.getColCount() == m2.getColCount(),"multiply_ABt: Inconsistent matrix sizes in multiplication!")
00738
00739
00740 if ((void*)&m1==(void*)&out|| (void*)&m2==(void*)&out)
00741 {
00742
00743 std::vector<T> temp(M1R*M2C);
00744
00745 T *ptr = &temp[0];
00746 for (size_t i=0; i < M1R; i++)
00747 for (size_t j=0; j < M2C; j++)
00748 {
00749 T accum = 0;
00750 for (size_t k=0; k < M1C; k++)
00751 accum += m1.get_unsafe(i,k) * m2.get_unsafe(j,k);
00752 *(ptr++) = accum;
00753 }
00754
00755 out.setSize(M1R,M2C);
00756 ptr = &temp[0];
00757 for (size_t i=0; i < M1R; i++)
00758 for (size_t j=0; j < M2C; j++)
00759 out.set_unsafe(i,j, *(ptr++) );
00760 }
00761 else
00762 {
00763
00764 out.setSize( M1R,M2C );
00765 for (size_t i=0; i < M1R; i++)
00766 for (size_t j=0; j < M2C; j++)
00767 {
00768 T accum = 0;
00769 for (size_t k=0; k < M1C; k++)
00770 accum += m1.get_unsafe(i,k) * m2.get_unsafe(j,k);
00771 out.set_unsafe(i,j,accum);
00772 }
00773 }
00774 MRPT_END
00775 }
00776
00777 template <class MAT_A,class MAT_B,class MAT_OUT>
00778 void multiply_result_is_symmetric(const MAT_A &m1,const MAT_B &m2, MAT_OUT &out)
00779 {
00780 MRPT_START
00781 typedef typename MAT_OUT::value_type T;
00782 const size_t M1R = m1.getRowCount();
00783 const size_t M1C = m1.getColCount();
00784 const size_t M2C = m2.getColCount();
00785
00786 ASSERTMSG_(m1.getColCount() == m2.getRowCount(),"multiply_result_is_symmetric: Inconsistent matrix sizes in multiplication!")
00787
00788
00789 if ((void*)&m1==(void*)&out || (void*)&m2==(void*)&out)
00790 {
00791
00792 std::vector<T> temp(M1R*M2C);
00793 T *ptr = &temp[0];
00794 for (size_t i=0; i < M1R; i++)
00795 for (size_t j=i; j < M2C; j++)
00796 {
00797 T accum = 0;
00798 for (size_t k=0; k < M1C; k++)
00799 accum += m1.get_unsafe(i,k) * m2.get_unsafe(k,j);
00800 *(ptr++) = accum;
00801 }
00802
00803
00804 out.setSize(M1R,M2C);
00805 ptr = &temp[0];
00806 for (size_t i=0; i < M1R; i++)
00807 for (size_t j=i; j < M1C; j++)
00808 out.get_unsafe(i,j) = out.get_unsafe(j,i) = *(ptr++);
00809 }
00810 else
00811 {
00812
00813 out.setSize( M1R,M2C );
00814 for (size_t i=0; i < M1R; i++)
00815 for (size_t j=i; j < M2C; j++)
00816 {
00817 T accum = 0;
00818 for (size_t k=0; k < M1C; k++)
00819 accum += m1.get_unsafe(i,k) * m2.get_unsafe(k,j);
00820 out.set_unsafe(i,j,accum);
00821 }
00822 for (size_t i=0; i < M1R; i++)
00823 for (size_t j=0; j<i; j++)
00824 out.get_unsafe(j,i) = out.get_unsafe(i,j);
00825 }
00826 MRPT_END
00827 }
00828
00829
00830 template <class MAT1,class MAT2>
00831 void insertMatrixTransposeInto( MAT1 &M,const size_t nRow,const size_t nCol,const MAT2 &in)
00832 {
00833 ASSERTMSG_( (nRow+size(in,2) <= M.getRowCount() ) && (nCol+size(in,1)<= M.getColCount()), "insertMatrix: Row or Col index out of bounds")
00834 for (size_t c=0;c<size(in,2);c++)
00835 for (size_t r=0;r<size(in,1);r++)
00836 M.get_unsafe(nRow+c,nCol+r) = in.get_unsafe(r,c);
00837 }
00838
00839
00840 template <class MAT1,class MAT2>
00841 void insertMatrixInto( MAT1 &M,const size_t nRow,const size_t nCol,const MAT2 &in)
00842 {
00843 ASSERTMSG_( (nRow+size(in,1) <= M.getRowCount() ) && (nCol+size(in,2) <= M.getColCount()), "insertMatrix: Row or Col index out of bounds")
00844 for (size_t r=0;r<size(in,1);r++)
00845 for (size_t c=0;c<size(in,2);c++)
00846 M.get_unsafe(nRow+r,nCol+c) = in.get_unsafe(r,c);
00847 }
00848
00849
00850 template <class MATORG, class MATDEST>
00851 void extractMatrix(
00852 const MATORG &M,
00853 const size_t first_row,
00854 const size_t first_col,
00855 MATDEST &outMat)
00856 {
00857 const size_t NR = outMat.getRowCount();
00858 const size_t NC = outMat.getColCount();
00859 ASSERTMSG_( (first_row+NR <= M.getRowCount() ) && (first_col+NC <= M.getColCount()), "extractMatrix: Row or Col index out of bounds")
00860 for (size_t r=0;r<NR;r++)
00861 for (size_t c=0;c<NC;c++)
00862 outMat.get_unsafe(r,c) = M.get_unsafe(first_row+r,first_col+c);
00863 }
00864
00865
00866
00867
00868
00869 template <class MATRIXIN,class MATRIXOUT>
00870 inline void invMatrix_special_2x2( const MATRIXIN &M, MATRIXOUT &out_inv )
00871 {
00872 typedef typename MATRIXIN::value_type T;
00873
00874
00875
00876 const T det = M.det();
00877 ASSERTMSG_(det!=0,"Singular matrix")
00878 const T det_inv = 1.0 / det;
00879 out_inv.setSize(2,2);
00880 out_inv._E(1,1) = M._E(2,2) * det_inv;
00881 out_inv._E(1,2) = -M._E(1,2) * det_inv;
00882 out_inv._E(2,1) = -M._E(2,1) * det_inv;
00883 out_inv._E(2,2) = M._E(1,1) * det_inv;
00884 }
00885 template <class MATRIXIN,class MATRIXOUT>
00886 inline void invMatrix_special_3x3( const MATRIXIN &M, MATRIXOUT &out_inv )
00887 {
00888 typedef typename MATRIXIN::value_type T;
00889
00890
00891
00892 const T det = M.det();
00893 ASSERTMSG_(det!=0,"Singular matrix")
00894 const T det_inv = 1.0 / det;
00895 out_inv.setSize(3,3);
00896 out_inv._E(1,1) = (M._E(3,3)*M._E(2,2)-M._E(3,2)*M._E(2,3) ) * det_inv;
00897 out_inv._E(1,2) = (-M._E(3,3)*M._E(1,2)+M._E(3,2)*M._E(1,3) )* det_inv;
00898 out_inv._E(1,3) = (M._E(2,3)*M._E(1,2)-M._E(2,2)*M._E(1,3) )* det_inv;
00899 out_inv._E(2,1) = (-M._E(3,3)*M._E(2,1)+M._E(3,1)*M._E(2,3))* det_inv;
00900 out_inv._E(2,2) = (M._E(3,3)*M._E(1,1)-M._E(3,1)*M._E(1,3))* det_inv;
00901 out_inv._E(2,3) = (-M._E(2,3)*M._E(1,1)+M._E(2,1)*M._E(1,3))* det_inv;
00902 out_inv._E(3,1) = (M._E(3,2)*M._E(2,1)-M._E(3,1)*M._E(2,2))* det_inv;
00903 out_inv._E(3,2) = (-M._E(3,2)*M._E(1,1)+M._E(3,1)*M._E(1,2))* det_inv;
00904 out_inv._E(3,3) = (M._E(2,2)*M._E(1,1)-M._E(2,1)*M._E(1,2))* det_inv;
00905 }
00906
00907
00908 template <> inline void invMatrix<CMatrixFixedNumeric<float,2,2>,CMatrixFixedNumeric<float,2,2> >( const CMatrixFixedNumeric<float,2,2> &M, CMatrixFixedNumeric<float,2,2> &out_inv ) { invMatrix_special_2x2(M,out_inv); }
00909 template <> inline void invMatrix_destroySrc<CMatrixFixedNumeric<float,2,2>,CMatrixFixedNumeric<float,2,2> >( CMatrixFixedNumeric<float,2,2> &M, CMatrixFixedNumeric<float,2,2> &out_inv ) { invMatrix_special_2x2(M,out_inv); }
00910 template <> inline void invMatrix<CMatrixFixedNumeric<double,2,2>,CMatrixFixedNumeric<double,2,2> >( const CMatrixFixedNumeric<double,2,2> &M, CMatrixFixedNumeric<double,2,2> &out_inv ) { invMatrix_special_2x2(M,out_inv); }
00911 template <> inline void invMatrix_destroySrc<CMatrixFixedNumeric<double,2,2>,CMatrixFixedNumeric<double,2,2> >( CMatrixFixedNumeric<double,2,2> &M, CMatrixFixedNumeric<double,2,2> &out_inv ) { invMatrix_special_2x2(M,out_inv); }
00912 template <> inline void invMatrix<CMatrixFixedNumeric<float,3,3>,CMatrixFixedNumeric<float,3,3> >( const CMatrixFixedNumeric<float,3,3> &M, CMatrixFixedNumeric<float,3,3> &out_inv ) { invMatrix_special_3x3(M,out_inv); }
00913 template <> inline void invMatrix_destroySrc<CMatrixFixedNumeric<float,3,3>,CMatrixFixedNumeric<float,3,3> >( CMatrixFixedNumeric<float,3,3> &M, CMatrixFixedNumeric<float,3,3> &out_inv ) { invMatrix_special_3x3(M,out_inv); }
00914 template <> inline void invMatrix<CMatrixFixedNumeric<double,3,3>,CMatrixFixedNumeric<double,3,3> >( const CMatrixFixedNumeric<double,3,3> &M, CMatrixFixedNumeric<double,3,3> &out_inv ) { invMatrix_special_3x3(M,out_inv); }
00915 template <> inline void invMatrix_destroySrc<CMatrixFixedNumeric<double,3,3>,CMatrixFixedNumeric<double,3,3> >( CMatrixFixedNumeric<double,3,3> &M, CMatrixFixedNumeric<double,3,3> &out_inv ) { invMatrix_special_3x3(M,out_inv); }
00916
00917 template <class MATRIXIN,class MATRIXOUT>
00918 inline void invMatrix( const MATRIXIN &M, MATRIXOUT &out_inv )
00919 {
00920 MAT_TYPE_SAMESIZE_OF(MATRIXIN) temp;
00921 temp.assignMatrix(M);
00922 invMatrix_destroySrc(temp,out_inv);
00923 }
00924
00925 template <class MATRIXIN,class MATRIXOUT>
00926 inline void invMatrix_destroySrc( MATRIXIN &M, MATRIXOUT &out_inv )
00927 {
00928 #if 0
00929 out_inv.setIdentity(M.getRowCount());
00930 mrpt::math::detail::fastLeftDivideSquare(out_inv,M);
00931 return;
00932 #else
00933 typedef typename MATRIXIN::value_type T;
00934 ASSERTMSG_(M.IsSquare(),"Inversion of non-square matrix")
00935
00936 const size_t NROWS = M.getRowCount();
00937 if (NROWS==3) return invMatrix_special_3x3(M,out_inv);
00938 else if (NROWS==2) return invMatrix_special_2x2(M,out_inv);
00939
00940
00941 T a1,a2;
00942 out_inv.setSize(NROWS,NROWS);
00943 out_inv.unit();
00944 for (size_t k=0; k < NROWS; k++)
00945 {
00946 int indx = M.pivot(k);
00947 if (indx == -1)
00948 THROW_EXCEPTION( "Inversion of a singular matrix");
00949
00950 if (indx != 0)
00951 out_inv.swapRows(k,indx);
00952
00953 a1 = M.get_unsafe(k,k);
00954 ASSERTDEB_(a1!=0)
00955 const T a1_i = 1/a1;
00956 for (size_t j=0; j < NROWS; j++)
00957 {
00958 M.get_unsafe(k,j) *= a1_i;
00959 out_inv.get_unsafe(k,j) *= a1_i;
00960 }
00961 for (size_t i=0; i < NROWS; i++)
00962 {
00963 if (i != k)
00964 {
00965 a2 = M.get_unsafe(i,k);
00966 for (size_t j=0; j < NROWS; j++)
00967 {
00968 M.get_unsafe(i,j) -= a2 * M.get_unsafe(k,j);
00969 out_inv.get_unsafe(i,j) -= a2 * out_inv.get_unsafe(k,j);
00970 }
00971 }
00972 }
00973 }
00974 #endif
00975 }
00976
00977
00978
00979
00980
00981
00982
00983 template <class MATRIX> inline typename MATRIX::value_type
00984 detMatrix_special_2x2(const MATRIX &M)
00985 {
00986 return M._E(1,1)*M._E(2,2) - M._E(1,2)*M._E(2,1);
00987 }
00988 template <class MATRIX> inline typename MATRIX::value_type
00989 detMatrix_special_3x3(const MATRIX &M)
00990 {
00991 return M._E(1,1)*(M._E(3,3)*M._E(2,2)-M._E(3,2)*M._E(2,3))-
00992 M._E(2,1)*(M._E(3,3)*M._E(1,2)-M._E(3,2)*M._E(1,3))+
00993 M._E(3,1)*(M._E(2,3)*M._E(1,2)-M._E(2,2)*M._E(1,3));
00994 }
00995 template <class MATRIX> typename MATRIX::value_type
00996 detMatrix_special_4x4(const MATRIX &M)
00997 {
00998 typedef typename MATRIX::value_type T;
00999 const T D1 = M._E(1+1,1+1)*(M._E(3+1,3+1)*M._E(2+1,2+1)-M._E(3+1,2+1)*M._E(2+1,3+1))-
01000 M._E(2+1,1+1)*(M._E(3+1,3+1)*M._E(1+1,2+1)-M._E(3+1,2+1)*M._E(1+1,3+1))+
01001 M._E(3+1,1+1)*(M._E(2+1,3+1)*M._E(1+1,2+1)-M._E(2+1,2+1)*M._E(1+1,3+1));
01002 const T D2 = M._E(1+1,1)*(M._E(3+1,3+1)*M._E(2+1,2+1)-M._E(3+1,2+1)*M._E(2+1,3+1))-
01003 M._E(2+1,1)*(M._E(3+1,3+1)*M._E(1+1,2+1)-M._E(3+1,2+1)*M._E(1+1,3+1))+
01004 M._E(3+1,1)*(M._E(2+1,3+1)*M._E(1+1,2+1)-M._E(2+1,2+1)*M._E(1+1,3+1));
01005 const T D3 = M._E(1+1,1)*(M._E(3+1,3+1)*M._E(2+1,2)-M._E(3+1,2)*M._E(2+1,3+1))-
01006 M._E(2+1,1)*(M._E(3+1,3+1)*M._E(1+1,2)-M._E(3+1,2)*M._E(1+1,3+1))+
01007 M._E(3+1,1)*(M._E(2+1,3+1)*M._E(1+1,2)-M._E(2+1,2)*M._E(1+1,3+1));
01008 const T D4 = M._E(1+1,1)*(M._E(3+1,3)*M._E(2+1,2)-M._E(3+1,2)*M._E(2+1,3))-
01009 M._E(2+1,1)*(M._E(3+1,3)*M._E(1+1,2)-M._E(3+1,2)*M._E(1+1,3))+
01010 M._E(3+1,1)*(M._E(2+1,3)*M._E(1+1,2)-M._E(2+1,2)*M._E(1+1,3));
01011 return M._E(1,1)*D1 - M._E(1,2)*D2 + M._E(1,3)*D3 - M._E(1,4)*D4;
01012 }
01013
01014
01015 template <> inline float detMatrix<CMatrixFixedNumeric<float,2,2> >(const CMatrixFixedNumeric<float,2,2> &M) { return detMatrix_special_2x2(M); }
01016 template <> inline double detMatrix<CMatrixFixedNumeric<double,2,2> >(const CMatrixFixedNumeric<double,2,2> &M) { return detMatrix_special_2x2(M); }
01017 template <> inline float detMatrix<CMatrixFixedNumeric<float,3,3> >(const CMatrixFixedNumeric<float,3,3> &M) { return detMatrix_special_3x3(M); }
01018 template <> inline double detMatrix<CMatrixFixedNumeric<double,3,3> >(const CMatrixFixedNumeric<double,3,3> &M) { return detMatrix_special_3x3(M); }
01019 template <> inline float detMatrix<CMatrixFixedNumeric<float,4,4> >(const CMatrixFixedNumeric<float,4,4> &M) { return detMatrix_special_4x4(M); }
01020 template <> inline double detMatrix<CMatrixFixedNumeric<double,4,4> >(const CMatrixFixedNumeric<double,4,4> &M) { return detMatrix_special_4x4(M); }
01021
01022 template <class MATRIX> RET_ELEMENT_ASSERT_MRPTCONTAINER(MATRIX)
01023 detMatrix(const MATRIX& M)
01024 {
01025 typedef typename MATRIX::value_type T;
01026 ASSERTMSG_(M.IsSquare(),"Inversion of non-square matrix")
01027
01028 const size_t NROWS = M.getRowCount();
01029 if (NROWS==3) return detMatrix_special_3x3(M);
01030 else if (NROWS==2) return detMatrix_special_2x2(M);
01031
01032 MAT_TYPE_SAMESIZE_OF(MATRIX) temp;
01033 temp.assignMatrix(M);
01034 T detVal = T(1);
01035 for (size_t k=0; k < NROWS; k++)
01036 {
01037 int indx = temp.pivot(k);
01038 if (indx == -1) return 0;
01039 if (indx != 0) detVal = - detVal;
01040 const T temp_kk = temp.get_unsafe(k,k);
01041 const T temp_kk_inv = T(1)/temp_kk;
01042 detVal = detVal * temp_kk;
01043 for (size_t i=k+1; i < NROWS; i++)
01044 {
01045 T piv = temp.get_unsafe(i,k)*temp_kk_inv;
01046 for (size_t j=k+1; j < NROWS; j++)
01047 temp.get_unsafe(i,j) -= piv * temp.get_unsafe(k,j);
01048 }
01049 }
01050 return detVal;
01051 }
01052
01053
01054
01055
01056 template <class MATRIX>
01057 int matrix_pivot(MATRIX &M, const size_t row)
01058 {
01059 typedef typename MATRIX::value_type T;
01060 size_t k = row;
01061 const size_t NROWS = M.getRowCount();
01062 T temp, amax = -1;
01063 for (size_t i=row; i < NROWS; i++)
01064 if ( (temp = std::abs( M.get_unsafe(i,row))) > amax && temp != 0)
01065 {
01066 amax = temp;
01067 k = i;
01068 }
01069 if (M.get_unsafe(k,row) == T(0)) return -1;
01070 if (k != row)
01071 {
01072 M.swapRows(k,row);
01073 return static_cast<int>( k );
01074 }
01075 return 0;
01076 }
01077
01078 template <class MAT,class VEC>
01079 void extractRowFromMatrix(const MAT &m, size_t nRow, VEC &out, const size_t startingCol = 0)
01080 {
01081 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
01082 if (nRow>=size(m,1))
01083 THROW_EXCEPTION("extractRow: Row index out of bounds");
01084 #endif
01085 const size_t n = size(m,2) - startingCol ;
01086 out.resize( n );
01087 for (size_t i=0;i<n;i++)
01088 out[i] = static_cast<typename MAT::value_type>( m.get_unsafe(nRow,i+startingCol));
01089 }
01090
01091 template <class MAT,class VEC>
01092 void extractColFromMatrix(const MAT &m, size_t nCol, VEC &out, const size_t startingRow = 0)
01093 {
01094 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
01095 if (nCol>=size(m,2))
01096 THROW_EXCEPTION("extractCol: Col index out of bounds");
01097 #endif
01098 const size_t n = size(m,1) - startingRow;
01099 out.resize( n );
01100 for (size_t i=0;i<n;i++)
01101 out[i] = static_cast<typename MAT::value_type>( m.get_unsafe(i+startingRow,nCol));
01102 }
01103
01104 template <class MAT,class VEC>
01105 void insertRowToMatrix(MAT &m, size_t nRow, const VEC &in, const size_t startingCol=0)
01106 {
01107 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
01108 if (nRow>=size(m,1))
01109 THROW_EXCEPTION("insertRow: Row index out of bounds");
01110 #endif
01111 ASSERT_( (size(m,2)-startingCol)==in.size() )
01112 const size_t n = size(m,2) - startingCol ;
01113 for (size_t i=0;i<n;i++)
01114 m.set_unsafe(nRow,i+startingCol, static_cast<typename MAT::value_type>(in[i]) );
01115 }
01116
01117 template <class MAT,class VEC>
01118 void insertColToMatrix(MAT &m, size_t nCol, const VEC &in, const size_t startingRow=0)
01119 {
01120 #if defined(_DEBUG) || (MRPT_ALWAYS_CHECKS_DEBUG_MATRICES)
01121 if (nCol>=size(m,2))
01122 THROW_EXCEPTION("insertCol: Col index out of bounds");
01123 #endif
01124 ASSERT_( (size(m,1)-startingRow)==in.size() )
01125 const size_t n = size(m,1) - startingRow;
01126 for (size_t i=0;i<n;i++)
01127 m.set_unsafe(i+startingRow,nCol, static_cast<typename MAT::value_type>(in[i]));
01128 }
01129
01130 template <class CONTAINER>
01131 void loadFromTextFileAsVector(CONTAINER &M, const std::string &file)
01132 {
01133 mrpt::math::CMatrixTemplateNumeric<double> MM;
01134 MM.loadFromTextFile(file);
01135 M.resize(MM.size());
01136 mrpt::utils::metaprogramming::copy_container_typecasting(MM,M);
01137 }
01138
01139 }
01140
01141
01142 template <class MAT1,class MAT2>
01143 inline typename MAT1::value_type multiply_HCHt_scalar(const MAT1 &H, const MAT2 &C) {
01144 return detail::multiply_HCHt_scalar(H,C);
01145 }
01146
01147
01148 template <class T>
01149 inline CMatrixTemplateNumeric<T> operator / (const CMatrixTemplateNumeric<T>& m1, const CMatrixTemplateNumeric<T>& m2)
01150 {
01151 return (m1 * !m2);
01152 }
01153
01154
01155 template <class T>
01156 inline CMatrixTemplateNumeric<T> operator ^ (const CMatrixTemplateNumeric<T>& m, const unsigned int pow)
01157 {
01158 CMatrixTemplateNumeric<T> temp(m);
01159 temp ^= pow;
01160 return temp;
01161 }
01162
01163
01164 template <class MAT>
01165 inline MAT_TYPE_TRANSPOSE_OF(MAT)
01166 operator ~ (const MAT& m)
01167 {
01168 const size_t R=m.getRowCount();
01169 const size_t C=m.getColCount();
01170 MAT_TYPE_TRANSPOSE_OF(MAT) temp; temp.setSize(C,R);
01171 for (size_t i=0;i<R;i++)
01172 for (size_t j=0;j<C;j++)
01173 temp.get_unsafe(j,i) = m.get_unsafe(i,j);
01174 return temp;
01175 }
01176
01177
01178 template <class MATRIX>
01179 inline RET_MAT_ASSERT_MRPTMATRIX(MATRIX)
01180 operator !(const MATRIX &m) {
01181 RET_MAT_ASSERT_MRPTMATRIX(MATRIX) ret(UNINITIALIZED_MATRIX);
01182 m.inv(ret);
01183 return ret;
01184 }
01185
01186
01187
01188
01189
01190
01191
01192
01193
01194
01195
01196
01197
01198 template <class MAT1,class MAT2>
01199 inline MAT_TYPE_PRODUCT_OF(MAT1,MAT2)
01200 operator * ( const MAT1 &A,
01201 const MAT2 &B )
01202 {
01203 MAT_TYPE_PRODUCT_OF(MAT1,MAT2) RES(UNINITIALIZED_MATRIX);
01204 detail::multiply_AB(A,B, RES);
01205 return RES;
01206 }
01207
01208
01209
01210
01211
01212
01213
01214 template<class MAT_IN, class MAT_OUT>
01215 void meanAndCov(
01216 const MAT_IN &v,
01217 vector_double &out_mean,
01218 MAT_OUT &out_cov
01219 )
01220 {
01221 const size_t N = v.getRowCount();
01222 ASSERTMSG_(N>0,"The input matrix contains no elements");
01223 const double N_inv = 1.0/N;
01224
01225 const size_t M = v.getColCount();
01226 ASSERTMSG_(M>0,"The input matrix contains rows of length 0");
01227
01228
01229 out_mean.assign(M,0);
01230 for (size_t i=0;i<N;i++)
01231 for (size_t j=0;j<M;j++)
01232 out_mean[j]+=v.get_unsafe(i,j);
01233 out_mean*=N_inv;
01234
01235
01236
01237
01238 out_cov.zeros(M,M);
01239 for (size_t i=0;i<N;i++)
01240 {
01241 for (size_t j=0;j<M;j++)
01242 out_cov.get_unsafe(j,j)+=square(v.get_unsafe(i,j)-out_mean[j]);
01243
01244 for (size_t j=0;j<M;j++)
01245 for (size_t k=j+1;k<M;k++)
01246 out_cov.get_unsafe(j,k)+=(v.get_unsafe(i,j)-out_mean[j])*(v.get_unsafe(i,k)-out_mean[k]);
01247 }
01248 for (size_t j=0;j<M;j++)
01249 for (size_t k=j+1;k<M;k++)
01250 out_cov.get_unsafe(k,j) = out_cov.get_unsafe(j,k);
01251 out_cov*=N_inv;
01252 }
01253
01254
01255
01256
01257
01258
01259 template<class MATRIX>
01260 inline MAT_TYPE_COVARIANCE_OF(MATRIX) cov( const MATRIX &v )
01261 {
01262 vector_double m;
01263 MAT_TYPE_COVARIANCE_OF(MATRIX) C;
01264 meanAndCov(v,m,C);
01265 return C;
01266 }
01267
01268
01269 #define SAVE_MATRIX(M) \
01270 M.saveToTextFile(mrpt::format("%s.txt",#M));
01271
01272
01273
01274 namespace detail {
01275
01276
01277
01278 template<typename T> class VicinityTraits<CMatrixTemplate<T> > {
01279 public:
01280 inline static void initialize(CMatrixTemplate<T> &mat,size_t N) {
01281 mat.setSize(N,N,true);
01282 }
01283 inline static void insertInContainer(CMatrixTemplate<T> &mat,size_t r,size_t c,const T &t) {
01284 mat.get_unsafe(r,c)=t;
01285 }
01286 };
01287
01288
01289
01290 template<typename T> class VicinityTraits<std::vector<T> > {
01291 public:
01292 inline static void initialize(std::vector<T> &vec,size_t N) {
01293 vec.reserve(N*N);
01294 }
01295 inline static void insertInContainer(std::vector<T> &vec,size_t,size_t,const T &t) {
01296 vec.push_back(t);
01297 }
01298 };
01299
01300
01301
01302
01303
01304
01305
01306
01307 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,4> {
01308 public:
01309 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01310 mat.ASSERT_ENOUGHROOM<1>(r,c);
01311 ReturnType res;
01312 VicinityTraits<ReturnType>::initialize(res,3);
01313 VicinityTraits<ReturnType>::insertInContainer(res,0,1,mat.get_unsafe(r-1,c));
01314 VicinityTraits<ReturnType>::insertInContainer(res,1,0,mat.get_unsafe(r,c-1));
01315 VicinityTraits<ReturnType>::insertInContainer(res,1,2,mat.get_unsafe(r,c+1));
01316 VicinityTraits<ReturnType>::insertInContainer(res,2,1,mat.get_unsafe(r+1,c));
01317 return res;
01318 }
01319 };
01320
01321
01322
01323
01324
01325
01326
01327
01328 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,5> {
01329 public:
01330 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01331 mat.ASSERT_ENOUGHROOM<1>(r,c);
01332 ReturnType res;
01333 VicinityTraits<ReturnType>::initialize(res,3);
01334 VicinityTraits<ReturnType>::insertInContainer(res,0,1,mat.get_unsafe(r-1,c));
01335 for (int i=-1;i<=1;++i) VicinityTraits<ReturnType>::insertInContainer(res,1,i+1,mat.get_unsafe(r,c+i));
01336 VicinityTraits<ReturnType>::insertInContainer(res,2,1,mat.get_unsafe(r+1,c));
01337 return res;
01338 }
01339 };
01340
01341
01342
01343
01344
01345
01346
01347
01348 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,8> {
01349 public:
01350 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01351 mat.ASSERT_ENOUGHROOM<1>(r,c);
01352 ReturnType res;
01353 VicinityTraits<ReturnType>::initialize(res,3);
01354 for (int i=-1;i<=1;++i) for (int j=-1;j<=1;++j) if (i||j) VicinityTraits<ReturnType>::insertInContainer(res,i+1,j+1,mat.get_unsafe(r+i,c+j));
01355 return res;
01356 }
01357 };
01358
01359
01360
01361
01362
01363
01364
01365
01366 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,9> {
01367 public:
01368 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01369 mat.ASSERT_ENOUGHROOM<1>(r,c);
01370 ReturnType res;
01371 VicinityTraits<ReturnType>::initialize(res,3);
01372 for (int i=-1;i<=1;++i) for (int j=-1;j<=1;++j) VicinityTraits<ReturnType>::insertInContainer(res,i+1,j+1,mat.get_unsafe(r+i,c+j));
01373 return res;
01374 }
01375 };
01376
01377
01378
01379
01380
01381
01382
01383
01384
01385
01386 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,12> {
01387 public:
01388 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01389 mat.ASSERT_ENOUGHROOM<2>(r,c);
01390 ReturnType res;
01391 VicinityTraits<ReturnType>::initialize(res,5);
01392 VicinityTraits<ReturnType>::insertInContainer(res,0,2,mat.get_unsafe(r-2,c));
01393 for (int i=-1;i<=1;++i) VicinityTraits<ReturnType>::insertInContainer(res,1,i+2,mat.get_unsafe(r-1,c+i));
01394 for (int i=-2;i<=2;++i) if (i) VicinityTraits<ReturnType>::insertInContainer(res,2,i+2,mat.get_unsafe(r,c+i));
01395 for (int i=-1;i<=1;++i) VicinityTraits<ReturnType>::insertInContainer(res,3,i+2,mat.get_unsafe(r+1,c+i));
01396 VicinityTraits<ReturnType>::insertInContainer(res,4,2,mat.get_unsafe(r+2,c));
01397 return res;
01398 }
01399 };
01400
01401
01402
01403
01404
01405
01406
01407
01408
01409
01410 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,13> {
01411 public:
01412 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01413 mat.ASSERT_ENOUGHROOM<2>(r,c);
01414 ReturnType res;
01415 VicinityTraits<ReturnType>::initialize(res,5);
01416 VicinityTraits<ReturnType>::insertInContainer(res,0,2,mat.get_unsafe(r-2,c));
01417 for (int i=-1;i<=1;++i) VicinityTraits<ReturnType>::insertInContainer(res,1,i+2,mat.get_unsafe(r-1,c+i));
01418 for (int i=-2;i<=2;++i) VicinityTraits<ReturnType>::insertInContainer(res,2,i+2,mat.get_unsafe(r,c+i));
01419 for (int i=-1;i<=1;++i) VicinityTraits<ReturnType>::insertInContainer(res,3,i+2,mat.get_unsafe(r+1,c+i));
01420 VicinityTraits<ReturnType>::insertInContainer(res,4,2,mat.get_unsafe(r+2,c));
01421 return res;
01422 }
01423 };
01424
01425
01426
01427
01428
01429
01430
01431
01432
01433
01434 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,20> {
01435 public:
01436 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01437 mat.ASSERT_ENOUGHROOM<2>(r,c);
01438 ReturnType res;
01439 VicinityTraits<ReturnType>::initialize(res,5);
01440 for (int i=-1;i<=1;++i) VicinityTraits<ReturnType>::insertInContainer(res,0,i+2,mat.get_unsafe(r-2,c+i));
01441 for (int i=-2;i<=2;++i) VicinityTraits<ReturnType>::insertInContainer(res,1,i+2,mat.get_unsafe(r-1,c+i));
01442 for (int i=-2;i<=2;++i) if (i) VicinityTraits<ReturnType>::insertInContainer(res,2,i+2,mat.get_unsafe(r,c+i));
01443 for (int i=-2;i<=2;++i) VicinityTraits<ReturnType>::insertInContainer(res,3,i+2,mat.get_unsafe(r+1,c+i));
01444 for (int i=-1;i<=1;++i) VicinityTraits<ReturnType>::insertInContainer(res,4,i+2,mat.get_unsafe(r+2,c+i));
01445 return res;
01446 }
01447 };
01448
01449
01450
01451
01452
01453
01454
01455
01456
01457
01458 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,21> {
01459 public:
01460 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01461 mat.ASSERT_ENOUGHROOM<2>(r,c);
01462 ReturnType res;
01463 VicinityTraits<ReturnType>::initialize(res,5);
01464 for (int i=-1;i<=1;++i) VicinityTraits<ReturnType>::insertInContainer(res,0,i+2,mat.get_unsafe(r-2,c+i));
01465 for (int i=-2;i<=2;++i) VicinityTraits<ReturnType>::insertInContainer(res,1,i+2,mat.get_unsafe(r-1,c+i));
01466 for (int i=-2;i<=2;++i) VicinityTraits<ReturnType>::insertInContainer(res,2,i+2,mat.get_unsafe(r,c+i));
01467 for (int i=-2;i<=2;++i) VicinityTraits<ReturnType>::insertInContainer(res,3,i+2,mat.get_unsafe(r+1,c+i));
01468 for (int i=-1;i<=1;++i) VicinityTraits<ReturnType>::insertInContainer(res,4,i+2,mat.get_unsafe(r+2,c+i));
01469 return res;
01470 }
01471 };
01472
01473
01474
01475
01476
01477
01478
01479
01480
01481
01482 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,24> {
01483 public:
01484 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01485 mat.ASSERT_ENOUGHROOM<2>(r,c);
01486 ReturnType res;
01487 VicinityTraits<ReturnType>::initialize(res,5);
01488 for (int i=-2;i<=2;++i) for (int j=-2;j<=2;++j) if (i||j) VicinityTraits<ReturnType>::insertInContainer(res,i+2,j+2,mat.get_unsafe(r+i,c+j));
01489 return res;
01490 }
01491 };
01492
01493
01494
01495
01496
01497
01498
01499
01500
01501
01502 template<typename MatrixType,typename T,typename ReturnType> struct getVicinity<MatrixType,T,ReturnType,25> {
01503 public:
01504 static ReturnType get(size_t r,size_t c,const MatrixType &mat) {
01505 mat.ASSERT_ENOUGHROOM<2>(r,c);
01506 ReturnType res;
01507 VicinityTraits<ReturnType>::initialize(res,5);
01508 for (int i=-2;i<=2;++i) for (int j=-2;j<=2;++j) VicinityTraits<ReturnType>::insertInContainer(res,i+2,j+2,mat.get_unsafe(r+i,c+j));
01509 return res;
01510 }
01511 };
01512
01513 template<typename MatrixType> size_t rank(const MatrixType &m,typename MatrixType::value_type eps) {
01514 size_t N=m.getRowCount();
01515 ASSERT_(m.getColCount()==N);
01516 MAT_TYPE_SAMESIZE_OF(MatrixType) tmp;
01517 tmp.assignMatrix(m);
01518 CArbitrarySubmatrixView<MatrixType> mat(tmp,0,N,0,N);
01519 size_t res=0;
01520 while (mat.getRowCount()!=0&&mat.getColCount()!=0) {
01521 size_t row=0;
01522 if (std::abs(mat(0,0)<=eps)) {
01523 for (size_t i=1;i<mat.getColCount();++i) if (std::abs(mat(i,0))>eps) {
01524 row=i;
01525 break;
01526 }
01527 if (row==0) {
01528 mat.deleteColumn(0);
01529 continue;
01530 }
01531 }
01532 size_t pRow=mat.getProxyRow(row);
01533 for (size_t i=0;i<mat.getRowCount();++i) {
01534 if (i==row) continue;
01535 size_t pRowAlt=mat.getProxyRow(i);
01536 typename MatrixType::value_type prop=mat.getWithRowProxied(pRowAlt,0)/mat.getWithRowProxied(pRow,0);
01537 for (size_t j=1;j<mat.getColCount();++j) mat.getWithRowProxied(pRowAlt,j)-=prop*mat.getWithRowProxied(pRow,j);
01538 }
01539 res++;
01540 mat.deleteColumn(0);
01541 mat.deleteRow(row);
01542 }
01543 return res;
01544 }
01545
01546 template<typename JA> void pivotUntilIdentity(JointAccessor<JA> &joint) {
01547 size_t N=joint.size();
01548
01549 for (size_t i=0;i<N-1;++i) {
01550
01551 joint.ensureSuitablePos(i);
01552 for (size_t j=i+1;j<N;++j) joint.substractRowAsNeeded(i,j);
01553 joint.unitarizeReducedRow(i);
01554 }
01555 joint.ensureAndUnitarizeLast();
01556
01557
01558 for (size_t i=N-1;i>0;--i) for (int j=i-1;j>=0;--j) joint.substractWhenReduced(i,j);
01559 }
01560
01561
01562 template <typename MAT1,typename MAT2,typename MAT3> inline void leftDivideSquare(const MAT1 &C,const MAT2 &A,MAT3 &RES) {
01563 MAT_TYPE_SAMESIZE_OF(MAT2) tmp;
01564 tmp.assignMatrix(A);
01565 RES.assignMatrix(C);
01566 fastLeftDivideSquare(RES,tmp);
01567 }
01568
01569
01570 template <typename MAT1,typename MAT2,typename MAT3> inline void rightDivideSquare(const MAT1 &C,const MAT2 &B, MAT3 &RES) {
01571 MAT_TYPE_SAMESIZE_OF(MAT2) tmp;
01572 tmp.assignMatrix(B);
01573 RES.assignMatrix(C);
01574 fastRightDivideSquare(RES,tmp);
01575 }
01576
01577
01578 template<typename MAT1,typename MAT2> inline void fastLeftDivideSquare(MAT1 &inout_CB,MAT2 &willBeDestroyed_A) {
01579 JointHorizontalAccessor<MAT2,MAT1> jha=JointHorizontalAccessor<MAT2,MAT1>(willBeDestroyed_A,inout_CB);
01580 JointAccessor<JointHorizontalAccessor<MAT2,MAT1> > ja=JointAccessor<JointHorizontalAccessor<MAT2,MAT1> >(jha);
01581 pivotUntilIdentity(ja);
01582 }
01583
01584
01585 template<typename MAT1,typename MAT2> inline void fastRightDivideSquare(MAT1 &inout_CA,MAT2 &willBeDestroyed_B) {
01586 JointVerticalAccessor<MAT2,MAT1> jva=JointVerticalAccessor<MAT2,MAT1>(willBeDestroyed_B,inout_CA);
01587 JointAccessor<JointVerticalAccessor<MAT2,MAT1> > ja=JointAccessor<JointVerticalAccessor<MAT2,MAT1> >(jva);
01588 pivotUntilIdentity(ja);
01589 }
01590
01591 }
01592
01593 }
01594 }
01595
01596
01597 #endif