newmat-1.10.4/0000755001161000116100000000000010426755356011311 5ustar rzrrzrnewmat-1.10.4/AUTHORS0000644001161000116100000000017110404772102012340 0ustar rzrrzrRobert Davies 16 Gloucester Street Wilton Wellington New Zealand robert at statsresearch.co.nz http://www.robertnz.com newmat-1.10.4/COPYING0000644001161000116100000000163610414046245012335 0ustar rzrrzrI place no restrictions on the use of newmat except that I take no liability for any problems that may arise from its use, distribution or other dealings with it. You can use it in your commercial projects. You can make and distribute modified or merged versions. You can include parts of it in your own software. If you distribute modified or merged versions, please make it clear which parts are mine and which parts are modified. For a substantially modified version, simply note that it is, in part, derived from my software. A comment in the code will be sufficient. The software is provided "as is", without warranty of any kind. Please understand that there may still be bugs and errors. Use at your own risk. I (Robert Davies) take no responsibility for any errors or omissions in this package or for any misfortune that may befall you or others as a result of your use, distribution or other dealings with it. newmat-1.10.4/README0000644001161000116100000000175510413660664012172 0ustar rzrrzrReadMe file for newmat10D - release version - 2 April, 2006 ------------------------------------------------------------ This is the release version of newmat10C. Newmat is a C++ library for manipulating matrices. Documentation is in nm10.htm. This library is freeware and may be freely used and distributed. To contact the author please email robert at statsresearch.co.nz Version 10D corrects an incompatibility with Gnu G++ 4.1. Version 10C makes the conditions of use compatible with Debian distribution, replaces include.h, myexcept.h, myexcept.cpp, precisio.h with recent versions, includes additional make files and makes a few minor corrections. Version 10B corrects incompatibilities with Gnu G++ version 3.4 and Intel C++ for Windows, 8.1. Include.h, myexcept.h, myexcept.cpp, precisio.h are replaced with recent versions. Version 10A corrects an error on the Kronecker production function and you can now run Gnu G++ version 3 and Intel for Linux without making any modifications. newmat-1.10.4/add_time.png0000644001161000116100000003563307422640644013572 0ustar rzrrzrPNG  IHDR}ֿgAMA a IDATxv8Pѫ?뿙 !`tA8;[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5a8~䶶ݒ#5ےǰL@q0>RSckGӥX* dڳs~j9O,'I=m >Bl)CCvα-lB@GN=~g)(BVYeT&y[fmְ[;: =i9O`UB`HytJ-,3b <!v.v@ftkǰl:HTdRSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5[R8m--Yla Vx!" Q!3KGs[2 9g琷dؾ:督K8XJRwU^[csDXui\GPYSf3z_#s:7:o>/Oگ_{|ooZ^Y;k֍e0ܩ׻u.z>y[}T]Gu{G ~Ǐ0[r*#L.Z1Y ǁK"!uA pӣzbcؗ?v*2lb @j\R-Ѕa5k@Od-53 2}w$|\JRb 4U8}?_N~ٛER[Yx'̮Ba@ "gm)uL8 YKm.tgLZjPl=H( YKm8=?vrC`*24Kw۾CBmy )B 58q#p YV"9n7RLӉ>=w,dmJ LE 5[]kgOvm@d-AxЦ;{M qt-Eb{'a ymݳ^ʭC--Ш 3vW晷wʔg(@dz|Q@n&K[MϦ2mn9 @d-(ws)ϳڿzi;h%S<2 LE7qORb 4m~JS\av8yu<7`u6ID+<?{oixCU^z%lzWd|Z MyЮM2[*YB[ѿkSG`--бSւpQ5B"-(W38F)Oς=1m}?=ӣW歬2fmb{Dž*s{rK/w_vKyBdm2fmbޝϜ5[[! eϮdwN-pYKm!c{79Oy f,` -;Bv(Hm(4u gl0Gο#kTdu,㏣q[8 גQl~=w@jα{OrtZ[YT'zm"#eb U}GֲWd-{( Xh 9BXLEG b @j-Nג<b Hkc_'Om{k߯ +YKr>aQk.e}d-)@{lkvkuU~ٛZR[Y 3/a@tٳy8ﮠZ=Q@[8 u9^Z2baů|LkJ^H֒0}?3a(/V!ME(g$b @j/4{X&y.. @-M ]lA9-م[y @ ۵py;)f>e[HYl.nNغ8@\g歬#c֦+W``uedUK.kX1kÞc [+я@ [H'Tdk[2 _lBT- Ӡ9 b @j-),q-@md%[5fOb @j-3#F'LRlHMx *[RSlHM'Oi ڋ@@-)@Ǩ-([9 $HŨ-sm,Rlt: b @j-smxPl31 b(f1|1RJ2 CϦ#oxlTzvkfe[-KGs[Z Y^+ykoa-/ c1 k@L9ݱ݌#cֆ*Nr5FCK ۻY СYk#Tf'LȐİ+ћ~E$HhE[+ӯqKa<a[iNg tM銭0qwQ| Qۯc:2x#RlTtGCWqHk|*i;s0Lgb 8Hoy%$Fmza.{l-2Ц3j Vpb{p=qe,-Pl/$l [4{!ױ4:pRlob!]Ξyen^drk:4 n:^iZ:9?fTuN C?ϙ=BPFp3b 4#}d?q xnP+_e\Plo24 i+RlՇ+7/a+w^{̬NKl)W^Ql+#[K pY̔گBTd#}tf2 *s_ӄ> m`c,ǙSV$Pa"ґZ1 ($`rȅ((T4aJTJmM-d{ -7Pl+3j ,Z8 PBˍJ§ގZ4;9̫uP;h?εn('_Î/xS~d0x~~ R1(cgfG\)Gl<,խrZ[<?~>%X8>Jք=RRr IѝFXGcЇ+Ty̍dYzYxn̜wޫ<Ëx֚ŶU>)r+)lC]0NS)~gep[)L+x^B2k5oKy}0ӂi}LaW>KWlK}O+;mraݐ%Z۰1w2cyA1΃ݣʭ]aՔڷ}~}v]gs36Zֆm ]=(cc ݠ+,srRr!GRo%7h.$SR~~T\CFl6b[Q[n}??q)GphC\̼b-o9K?Dߗ,H1I9hIbG-<>Odk#7WJNӷ`Jލ=[#UGm G]4ZX`asڟց89Բeyrrl-gw&Fl{8g~C˞ݑxiKU]yͅ d6ꣶӅ=[}XGf{el3Y3 7[JByc,^e>a$߱e;pq֔c/Wloy SB:Pj y{qlUΨ(-Dߗ|6pɦ%sǛA? D*LnR  ~an~d;]v._{};ďqs6fZ,\ Tl˔RKeYhalUاF4dېMENj~qD=@_vq> l[ >Qj\Flybzvln5)ZؗjBְg(}_@{Ls{~~Zڗlwܖb{#E/Wlo棷ws!Zھ5-oW嶔J=sA{)RKJm tc?Y%T>,.ŕZݗ3kxC#gEߗ[{.?z=t/ulel_\R 1b/X|=;Fk],;/Ϭ3oK8EY.Wu(L9V1LiZi_Qogk܅(mھFkCRm tm) .(.E ˳u(2J--/WloC6BW>44x)侼!oa=td[Z}_؞^n)@e޾$gxWj)z?( p7Hm tG])w-μc8ľ<6-19 Pz"\ jX* .k~|Vl^GQ"-/Wlo^NUmZ/nT۳NĆb 2툾/Wlo(*!~ۈjc}]&\ "Z-kUJ-ؗfg+Q_ZZ}_@-eWѭbԺXٗfo9La>[#iP}b|e^j꜂ c}.ݏ?1d#/WloV*]Em7<&l9=FEߗ+7P[G"|fٯqؗfĵk*ޭj>a)0έ 7UL;%@?Vև..htU7g:+o{>-s겇̅{[ AfWskfmzZl;|~neT72y˒myr]WwFl3Cz83ޑXcŃ]ѽޜ̼p x^=wuN7bڰ=ݩ=7M"k/#޻Ӽc'{}}Md8i?tjOzyϊL}zgZŶ=%ƓE|1>7z#(T_ dqS/rv?by@ d-W;[RKwm)}`<NEb "b @j-)b @j-)b @j-)b @j-[{jX{1n0bzf} \ȏ]1ɑ׵'Z/Y[j!gP{]k>-gmv@li]^ԑv{]Ϭ1k=#<ֵp>9Dֶ\%kK~K޶]NE#C/j=z׺91x7{W˺g)}۞ԽlK/YJ_c0 RW=m^ֵ,ue=Kk]][ra>{ !j%k[RO3EVdZBYX ^%-)p˫"SO5dal9Uk%5cw=>ggDXڏ>'"kOdm{ϵ^y;B<|Zڮ- @j-)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-)ڿZ1 CqϏ֖[mY3qm-L+@ a|ƛ3cGqm@LE}6xvPKKy*g[84Ze9O{)piO[ClwGO9y0DB"`Z ūsQGZɎNzR@-èy<6-hm֐Y;:.U!g!wՄ\MB+Nʿ!'y|9θ)f*2)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-)b @j-[{ qWm6,0 +GЊS(\OЊ-ʳs[HQl_Q c6R-@lJۈY;%w86Or;GnoZ;Y~e׈?κ 2~{m7ֻr]}=z7-u,9zY~e>z\t}D\;nzsLyq}};zgɃ6DЂSatъq]si'ohEb*8q,e>h1\zΥXoآ}(wyfw_7Q [(b @j-Ѕa5ks WDIRSȫ"i^|wYK}-мW8v|;!goN=k^FIDATKi;oeb t0:pgC"gm)umTN4鎿^Zjs(+gM>cjDRb 4GB^ZjƱ﹮0Ȑ cz_N#w!,Y[_}[Rs(9 אlL l, kF&`=kgOvmr9WHsl6q>Ϗ]キ }[m7$}V5v;cGsuަZ&M6tuO{w ӳ?sz\x%Vgٳ+Yݭӣ #y AR[b^`g#ohEb*8+O޾T 45 k/K!Gl24ͱZ2b pP2N7 ^}6,P){,A d-{)'1E 4M*Y{L,+"iUAy{Ef-ENRLE8MGkN0d-k[ʸtFxzfWd-{( 2Z[b6=|N\G88ir֖vxZۗ*@~w]-E6N+G}1k^ڦ6Z[Gl= %Z Z T"k Ȉ- ϕGtp(-Mi b nE1 YۅVKm)" bl~HR[ _l#0˘#lhm)/,@G'4ЍJ]b; C1p|P<o_H3Jz8pخ!~0yÛ6 ~^a3jveRy{TyiU6 )93og-ЭͅvK>%ety,3ptggYk:2pv)w6]=J )1MThIWl\2@o^N9v +tv# oG8Q8Ӧsh/|] Q ʞγ\h?~%m&B:c*^i(@v}R?=$b gy̜{dͦQZ6%dB|QhڔLExl9[ x \8՘rL:MGOYYn-c5 pś3OCb:Gi^6NvsajpE ݲ/O8 LFhvJuFxM6gu!RĪ}5rԲG,Ho穝jg]AaB7k?̮rԲb ¥˗*9#LEl9CGMUzAJ-G#XQaapR;[W~Qh4\v-[:w)k=5/v()R LGvb*? Ia i-cB˽z[׺ gCM,πk}> mLE|*,3 m=gvMu_r!Ŷ,[lBa>nu-|QjsȘa"i__2% 1r8:}Z}m'g7$vsud;DgoaĶ2ӑ iR~׸ɐQ[K)gX)?8MOȣǃӮrtv_s3 Yh57#jަ4jK;^!*}O< Ǐ;fU)ćc_βܮmtvKim7I7b<)?n+wtT,ғKPlO*R-,$ɺ0m1;hzP t[y#]}LG&2Zgۓ:ja׈B 4Rj\[5+6{PC+C*- K,2!/*o#rWOS^.}zT>gErdl-X=kL|.mրxf}ɴ*<^hЎD{Wwy`|Y*(W5 V*aųa c _au;/=c"ŖZ8=}9>/k:ev[EZ#7Ks06͂K0-c_=3@|묌/?y`JA8FJBV`sN>rϒ:ܥ4_E^29mkhvzt n>W/>X ؘiYgѾYkzuF*Sc~w[wR%Q`<)@S.4.$%{3ZKc"˟gW8 ?y/<ηNIR ǙkD!8bn,x˻QVbRlbĶd-OW ߏ0tǨm^!De}{cvc ns Q[vxTHӐ<-f,~'/gY#o>;Gl]4 &ShQ>?럧ť)s/tR 3bCQl1b;Sb $Ҿ"n\4*|*ţaՂ׈H{5y-[SpLy{uJ-/e-q|FrׯiRJ,tռMw6+mm՞ܪVnk^[ ݻqv{Ӥ;U9֎87έ.<3ݛm!kMC&Rض~UFn5nZ$ p&Fl9zԵ#1橭Wi4ZKpQۭ93oowAGˬ﷗_#;r0ֹ>s5dqݢ86{J2=p EgIWl{"R,$[^ qiD6Z KWl[=,UϷm3$oQn:pVBwl/X}y2mv2ï2=n"E-<݈muOG_PJi$šX <2+h-\Èm#ܫ:r[w{率h-eٗ*9#ª~,oʮߤZ/WlopЖskiC}y2owwS28 MZ}_@sAVnu~RK~9uTaS\bʿ1ZK+g}ƬcCěUc UI%d ψm# "\( =hi,o5 y(k7Eߗ+7{CzXzI\2ka_޲ֶO"od2-/q? xze>`=QMcj{GO?qGhܬZھ5-oS.L!{iA}G)ϱ|휚\J^Nӣq_(\?v>@R#[ej ;^kfT7#<R nhҢVe1zk .E]G.,UoBh ZߗgI;5Oe2-/Wlo3G[bV/Ϭ )bDߗ*r\qԻb\ i|퍴iO͑7 ̈m#WۛSGo?Nn~ 5ˣ}~;:;"Sh-/7b۹ϖcGYz,w?swZtodY#~j/ tƈm#5 mh-=/Xe4WbEߗ=MC@}礥N`ZΤFsR&oQlyjO> ԥ?;06Uyooc%9ӟ7hc(.5)lrdpJ|w^hǯcƒ y-}L4X^ ernPbnkew7ݎGɺhRWy;mY4!l1o;z;=~Lzqt Íu >B;Ŗٗfĵ?NmƵl~~[oY yS(&7)[G}b|joV}Xxy7~Zz`_ۙg8p191,׉kVBu-!`9«e.8 J> lu)'r3 wDz߂Ol,Gϓ-Qed-/y@z)""*RwfӡZw_z]﫝nݗ;:]z@?:1{GN@[Z[Ow('Oيpq#.q}M">#.ozG}\{\YZG}O#,;3oe-@"gmG-Zf*2)Rx` LE 5[RSlHM 5[RSlHM 5[RSlHM 5[R4 CDZbbi]a} 3ca]k?g#kOdm{ϵ^y;B<|ZnnҺ#dڻY33cpzFx "k}ru퉬mK֖"o[˙-m=keGr^z,u]scnX sue=Kg]{YRZ%=dm#=={YWٖ^ֳuͫ`>jȚB=?s>Kjbzf} \ȏ]1} OD^מkdm)vy,Cu8][3[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5[RSlHM 5|&-IENDB`newmat-1.10.4/bandmat.cpp0000644001161000116100000003675407421435236013433 0ustar rzrrzr//$$ bandmat.cpp Band matrix definitions // Copyright (C) 1991,2,3,4,9: R B Davies #define WANT_MATH // include.h will get math fns //#define WANT_STREAM #include "include.h" #include "newmat.h" #include "newmatrc.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,10); ++ExeCount; } #else #define REPORT {} #endif static inline int my_min(int x, int y) { return x < y ? x : y; } static inline int my_max(int x, int y) { return x > y ? x : y; } BandMatrix::BandMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::BM); GetMatrix(gmx); CornerClear(); } void BandMatrix::SetParameters(const GeneralMatrix* gmx) { REPORT MatrixBandWidth bw = gmx->BandWidth(); lower = bw.lower; upper = bw.upper; } void BandMatrix::ReSize(int n, int lb, int ub) { REPORT Tracer tr("BandMatrix::ReSize"); if (lb<0 || ub<0) Throw(ProgramException("Undefined bandwidth")); lower = (lb<=n) ? lb : n-1; upper = (ub<=n) ? ub : n-1; GeneralMatrix::ReSize(n,n,n*(lower+1+upper)); CornerClear(); } // SimpleAddOK shows when we can add etc two matrices by a simple vector add // and when we can add one matrix into another // *gm must be the same type as *this // return 0 if simple add is OK // return 1 if we can add into *gm only // return 2 if we can add into *this only // return 3 if we can't add either way // For SP this will still be valid if we swap 1 and 2 short BandMatrix::SimpleAddOK(const GeneralMatrix* gm) { const BandMatrix* bm = (const BandMatrix*)gm; if (bm->lower == lower && bm->upper == upper) { REPORT return 0; } else if (bm->lower >= lower && bm->upper >= upper) { REPORT return 1; } else if (bm->lower <= lower && bm->upper <= upper) { REPORT return 2; } else { REPORT return 3; } } short SymmetricBandMatrix::SimpleAddOK(const GeneralMatrix* gm) { const SymmetricBandMatrix* bm = (const SymmetricBandMatrix*)gm; if (bm->lower == lower) { REPORT return 0; } else if (bm->lower > lower) { REPORT return 1; } else { REPORT return 2; } } void UpperBandMatrix::ReSize(int n, int lb, int ub) { REPORT if (lb != 0) { Tracer tr("UpperBandMatrix::ReSize"); Throw(ProgramException("UpperBandMatrix with non-zero lower band" )); } BandMatrix::ReSize(n, lb, ub); } void LowerBandMatrix::ReSize(int n, int lb, int ub) { REPORT if (ub != 0) { Tracer tr("LowerBandMatrix::ReSize"); Throw(ProgramException("LowerBandMatrix with non-zero upper band" )); } BandMatrix::ReSize(n, lb, ub); } void BandMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("BandMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } MatrixBandWidth mbw = A.BandWidth(); ReSize(n, mbw.Lower(), mbw.Upper()); } bool BandMatrix::SameStorageType(const GeneralMatrix& A) const { if (Type() != A.Type()) { REPORT return false; } REPORT return BandWidth() == A.BandWidth(); } void BandMatrix::ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B) { REPORT Tracer tr("BandMatrix::ReSizeForAdd"); MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); if ((A_BW.Lower() < 0) | (A_BW.Upper() < 0) | (B_BW.Lower() < 0) | (A_BW.Upper() < 0)) Throw(ProgramException("Can't ReSize to BandMatrix" )); // already know A and B are square ReSize(A.Nrows(), my_max(A_BW.Lower(), B_BW.Lower()), my_max(A_BW.Upper(), B_BW.Upper())); } void BandMatrix::ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B) { REPORT Tracer tr("BandMatrix::ReSizeForSP"); MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); if ((A_BW.Lower() < 0) | (A_BW.Upper() < 0) | (B_BW.Lower() < 0) | (A_BW.Upper() < 0)) Throw(ProgramException("Can't ReSize to BandMatrix" )); // already know A and B are square ReSize(A.Nrows(), my_min(A_BW.Lower(), B_BW.Lower()), my_min(A_BW.Upper(), B_BW.Upper())); } void BandMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::BM); CornerClear(); } void BandMatrix::CornerClear() const { // set unused parts of BandMatrix to zero REPORT int i = lower; Real* s = store; int bw = lower + 1 + upper; while (i) { int j = i--; Real* sj = s; s += bw; while (j--) *sj++ = 0.0; } i = upper; s = store + storage; while (i) { int j = i--; Real* sj = s; s -= bw; while (j--) *(--sj) = 0.0; } } MatrixBandWidth MatrixBandWidth::operator+(const MatrixBandWidth& bw) const { REPORT int l = bw.lower; int u = bw.upper; l = (lower < 0 || l < 0) ? -1 : (lower > l) ? lower : l; u = (upper < 0 || u < 0) ? -1 : (upper > u) ? upper : u; return MatrixBandWidth(l,u); } MatrixBandWidth MatrixBandWidth::operator*(const MatrixBandWidth& bw) const { REPORT int l = bw.lower; int u = bw.upper; l = (lower < 0 || l < 0) ? -1 : lower+l; u = (upper < 0 || u < 0) ? -1 : upper+u; return MatrixBandWidth(l,u); } MatrixBandWidth MatrixBandWidth::minimum(const MatrixBandWidth& bw) const { REPORT int l = bw.lower; int u = bw.upper; if ((lower >= 0) && ( (l < 0) || (l > lower) )) l = lower; if ((upper >= 0) && ( (u < 0) || (u > upper) )) u = upper; return MatrixBandWidth(l,u); } UpperBandMatrix::UpperBandMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::UB); GetMatrix(gmx); CornerClear(); } void UpperBandMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::UB); CornerClear(); } LowerBandMatrix::LowerBandMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::LB); GetMatrix(gmx); CornerClear(); } void LowerBandMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::LB); CornerClear(); } BandLUMatrix::BandLUMatrix(const BaseMatrix& m) { REPORT Tracer tr("BandLUMatrix"); storage2 = 0; store2 = 0; // in event of exception during build GeneralMatrix* gm = ((BaseMatrix&)m).Evaluate(MatrixType::BM); m1 = ((BandMatrix*)gm)->lower; m2 = ((BandMatrix*)gm)->upper; GetMatrix(gm); if (nrows!=ncols) Throw(NotSquareException(*this)); d = true; sing = false; indx = new int [nrows]; MatrixErrorNoSpace(indx); MONITOR_INT_NEW("Index (BndLUMat)",nrows,indx) storage2 = nrows * m1; store2 = new Real [storage2]; MatrixErrorNoSpace(store2); MONITOR_REAL_NEW("Make (BandLUMat)",storage2,store2) ludcmp(); } BandLUMatrix::~BandLUMatrix() { REPORT MONITOR_INT_DELETE("Index (BndLUMat)",nrows,indx) MONITOR_REAL_DELETE("Delete (BndLUMt)",storage2,store2) delete [] indx; delete [] store2; } MatrixType BandLUMatrix::Type() const { REPORT return MatrixType::BC; } LogAndSign BandLUMatrix::LogDeterminant() const { REPORT if (sing) return 0.0; Real* a = store; int w = m1+1+m2; LogAndSign sum; int i = nrows; // while (i--) { sum *= *a; a += w; } if (i) for (;;) { sum *= *a; if (!(--i)) break; a += w; } if (!d) sum.ChangeSign(); return sum; } GeneralMatrix* BandMatrix::MakeSolver() { REPORT GeneralMatrix* gm = new BandLUMatrix(*this); MatrixErrorNoSpace(gm); gm->ReleaseAndDelete(); return gm; } void BandLUMatrix::ludcmp() { REPORT Real* a = store2; int i = storage2; // clear store2 - so unused locations are always zero - // required by operator== while (i--) *a++ = 0.0; a = store; i = m1; int j = m2; int k; int n = nrows; int w = m1 + 1 + m2; while (i) { Real* ai = a + i; k = ++j; while (k--) *a++ = *ai++; k = i--; while (k--) *a++ = 0.0; } a = store; int l = m1; for (k=0; k=mini; i--) { Real* b = B + i; Real* bk = b; Real x = *bk; Real* a = store + w*i; Real y = *a; int k = l+m1; while (k--) x -= *(++a) * *(++bk); *b = x / y; if (l < m2) l++; } } void BandLUMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip; Real* el = mcin.data-i; Real* el1=el; while (i--) *el++ = 0.0; el += mcin.storage; i = nrows - mcin.skip - mcin.storage; while (i--) *el++ = 0.0; lubksb(el1, mcout.skip); } // Do we need check for entirely zero output? void UpperBandMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip-mcout.skip; Real* elx = mcin.data-i; while (i-- > 0) *elx++ = 0.0; int nr = mcin.skip+mcin.storage; elx = mcin.data+mcin.storage; Real* el = elx; int j = mcout.skip+mcout.storage-nr; i = nr-mcout.skip; while (j-- > 0) *elx++ = 0.0; Real* Ael = store + (upper+1)*(i-1)+1; j = 0; if (i > 0) for(;;) { elx = el; Real sum = 0.0; int jx = j; while (jx--) sum += *(--Ael) * *(--elx); elx--; *elx = (*elx - sum) / *(--Ael); if (--i <= 0) break; if (j 0) *elx++ = 0.0; int nc = mcin.skip; i = nc+mcin.storage; elx = mcin.data+mcin.storage; int nr = mcout.skip+mcout.storage; int j = nr-i; i = nr-nc; while (j-- > 0) *elx++ = 0.0; Real* el = mcin.data; Real* Ael = store + (lower+1)*nc + lower; j = 0; if (i > 0) for(;;) { elx = el; Real sum = 0.0; int jx = j; while (jx--) sum += *Ael++ * *elx++; *elx = (*elx - sum) / *Ael++; if (--i <= 0) break; if (jReleaseAndDelete(); return gm; } SymmetricBandMatrix::SymmetricBandMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::SB); GetMatrix(gmx); } GeneralMatrix* SymmetricBandMatrix::Transpose(TransposedMatrix*, MatrixType mt) { REPORT return Evaluate(mt); } LogAndSign SymmetricBandMatrix::LogDeterminant() const { REPORT BandLUMatrix C(*this); return C.LogDeterminant(); } void SymmetricBandMatrix::SetParameters(const GeneralMatrix* gmx) { REPORT lower = gmx->BandWidth().lower; } void SymmetricBandMatrix::ReSize(int n, int lb) { REPORT Tracer tr("SymmetricBandMatrix::ReSize"); if (lb<0) Throw(ProgramException("Undefined bandwidth")); lower = (lb<=n) ? lb : n-1; GeneralMatrix::ReSize(n,n,n*(lower+1)); } void SymmetricBandMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("SymmetricBandMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } MatrixBandWidth mbw = A.BandWidth(); int b = mbw.Lower(); if (b != mbw.Upper()) { Tracer tr("SymmetricBandMatrix::ReSize(GM)"); Throw(ProgramException("Upper and lower band-widths not equal")); } ReSize(n, b); } bool SymmetricBandMatrix::SameStorageType(const GeneralMatrix& A) const { if (Type() != A.Type()) { REPORT return false; } REPORT return BandWidth() == A.BandWidth(); } void SymmetricBandMatrix::ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B) { REPORT Tracer tr("SymmetricBandMatrix::ReSizeForAdd"); MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); if ((A_BW.Lower() < 0) | (B_BW.Lower() < 0)) Throw(ProgramException("Can't ReSize to SymmetricBandMatrix" )); // already know A and B are square ReSize(A.Nrows(), my_max(A_BW.Lower(), B_BW.Lower())); } void SymmetricBandMatrix::ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B) { REPORT Tracer tr("SymmetricBandMatrix::ReSizeForSP"); MatrixBandWidth A_BW = A.BandWidth(); MatrixBandWidth B_BW = B.BandWidth(); if ((A_BW.Lower() < 0) | (B_BW.Lower() < 0)) Throw(ProgramException("Can't ReSize to SymmetricBandMatrix" )); // already know A and B are square ReSize(A.Nrows(), my_min(A_BW.Lower(), B_BW.Lower())); } void SymmetricBandMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::SB); } void SymmetricBandMatrix::CornerClear() const { // set unused parts of BandMatrix to zero REPORT int i = lower; Real* s = store; int bw = lower + 1; if (i) for(;;) { int j = i; Real* sj = s; while (j--) *sj++ = 0.0; if (!(--i)) break; s += bw; } } MatrixBandWidth SymmetricBandMatrix::BandWidth() const { REPORT return MatrixBandWidth(lower,lower); } inline Real square(Real x) { return x*x; } Real SymmetricBandMatrix::SumSquare() const { REPORT CornerClear(); Real sum1=0.0; Real sum2=0.0; Real* s=store; int i=nrows; int l=lower; while (i--) { int j = l; while (j--) sum2 += square(*s++); sum1 += square(*s++); } ((GeneralMatrix&)*this).tDelete(); return sum1 + 2.0 * sum2; } Real SymmetricBandMatrix::SumAbsoluteValue() const { REPORT CornerClear(); Real sum1=0.0; Real sum2=0.0; Real* s=store; int i=nrows; int l=lower; while (i--) { int j = l; while (j--) sum2 += fabs(*s++); sum1 += fabs(*s++); } ((GeneralMatrix&)*this).tDelete(); return sum1 + 2.0 * sum2; } Real SymmetricBandMatrix::Sum() const { REPORT CornerClear(); Real sum1=0.0; Real sum2=0.0; Real* s=store; int i=nrows; int l=lower; while (i--) { int j = l; while (j--) sum2 += *s++; sum1 += *s++; } ((GeneralMatrix&)*this).tDelete(); return sum1 + 2.0 * sum2; } #ifdef use_namespace } #endif newmat-1.10.4/boolean.h0000644001161000116100000000112206522544614013070 0ustar rzrrzr//$$ boolean.h bool class // This is for compilers that do not have bool automatically defined #ifndef bool_LIB #define bool_LIB 0 #ifdef use_namespace namespace RBD_COMMON { #endif class bool { int value; public: bool(const int b) { value = b ? 1 : 0; } bool(const void* b) { value = b ? 1 : 0; } bool() {} operator int() const { return value; } int operator!() const { return !value; } }; const bool true = 1; const bool false = 0; // version for some older versions of gnu g++ //#define false 0 //#define true 1 #ifdef use_namespace } #endif #endif newmat-1.10.4/cholesky.cpp0000644001161000116100000000404007414433266013630 0ustar rzrrzr//$$ cholesky.cpp cholesky decomposition // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH //#define WANT_STREAM #include "include.h" #include "newmat.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,14); ++ExeCount; } #else #define REPORT {} #endif /********* Cholesky decomposition of a positive definite matrix *************/ // Suppose S is symmetrix and positive definite. Then there exists a unique // lower triangular matrix L such that L L.t() = S; inline Real square(Real x) { return x*x; } ReturnMatrix Cholesky(const SymmetricMatrix& S) { REPORT Tracer trace("Cholesky"); int nr = S.Nrows(); LowerTriangularMatrix T(nr); Real* s = S.Store(); Real* t = T.Store(); Real* ti = t; for (int i=0; i=(ControlWord i) const { return (cw & i.cw) == i.cw; } bool operator<=(ControlWord i) const { return (cw & i.cw) == cw; } // flip selected bits ControlWord operator^(ControlWord i) const { return ControlWord(cw ^ i.cw); } ControlWord operator~() const { return ControlWord(~cw); } // convert to integer int operator+() const { return cw; } int operator!() const { return cw==0; } FREE_CHECK(ControlWord) }; #endif newmat-1.10.4/evalue.cpp0000644001161000116100000002177607417717456013320 0ustar rzrrzr//$$evalue.cpp eigen-value decomposition // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH #include "include.h" #include "newmatap.h" #include "newmatrm.h" #include "precisio.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,17); ++ExeCount; } #else #define REPORT {} #endif static void tred2(const SymmetricMatrix& A, DiagonalMatrix& D, DiagonalMatrix& E, Matrix& Z) { Tracer et("Evalue(tred2)"); REPORT Real tol = FloatingPointPrecision::Minimum()/FloatingPointPrecision::Epsilon(); int n = A.Nrows(); Z.ReSize(n,n); Z.Inject(A); D.ReSize(n); E.ReSize(n); Real* z = Z.Store(); int i; for (i=n-1; i > 0; i--) // i=0 is excluded { Real f = Z.element(i,i-1); Real g = 0.0; int k = i-1; Real* zik = z + i*n; while (k--) g += square(*zik++); Real h = g + square(f); if (g <= tol) { REPORT E.element(i) = f; h = 0.0; } else { REPORT g = sign(-sqrt(h), f); E.element(i) = g; h -= f*g; Z.element(i,i-1) = f-g; f = 0.0; Real* zji = z + i; Real* zij = z + i*n; Real* ej = E.Store(); int j; for (j=0; j=l; i--) { Real ei = E.element(i); Real di = D.element(i); Real& ei1 = E.element(i+1); g = c * ei; h = c * p; if ( fabs(p) >= fabs(ei)) { REPORT c = ei / p; r = sqrt(c*c + 1.0); ei1 = s*p*r; s = c/r; c = 1.0/r; } else { REPORT c = p / ei; r = sqrt(c*c + 1.0); ei1 = s * ei * r; s = 1.0/r; c /= r; } p = c * di - s*g; D.element(i+1) = h + s * (c*g + s*di); Real* zki = z + i; Real* zki1 = zki + 1; int k = n; if (k) for (;;) { REPORT h = *zki1; *zki1 = s*(*zki) + c*h; *zki = c*(*zki) - s*h; if (!(--k)) break; zki += n; zki1 += n; } } el = s*p; dl = c*p; if (fabs(el) <= b) { REPORT; test = true; break; } } if (!test) Throw ( ConvergenceException(D) ); dl += f; } /* for (int i=0; i= 0; i--) { Real h = 0.0; Real f = - FloatingPointPrecision::Maximum(); Real* d = D.Store(); Real* a = A.Store() + (i*(i+1))/2; int k = i; while (k--) { f = *a++; *d++ = f; h += square(f); } if (h <= tol) { REPORT *(--ei) = 0.0; h = 0.0; } else { REPORT Real g = sign(-sqrt(h), f); *(--ei) = g; h -= f*g; f -= g; *(d-1) = f; *(a-1) = f; f = 0.0; Real* dj = D.Store(); Real* ej = E.Store(); int j; for (j = 0; j < i; j++) { Real* dk = D.Store(); Real* ak = A.Store()+(j*(j+1))/2; Real g = 0.0; k = j; while (k--) g += *ak++ * *dk++; k = i-j; int l = j; if (k) for (;;) { g += *ak * *dk++; if (!(--k)) break; ak += ++l; } g /= h; *ej++ = g; f += g * *dj++; } Real hh = f / (2 * h); Real* ak = A.Store(); dj = D.Store(); ej = E.Store(); for (j = 0; j < i; j++) { f = *dj++; g = *ej - hh * f; *ej++ = g; Real* dk = D.Store(); Real* ek = E.Store(); k = j+1; while (k--) { *ak++ -= (f * *ek++ + g * *dk++); } } } *d = *a; *a = h; } } static void tql1(DiagonalMatrix& D, DiagonalMatrix& E) { Tracer et("Evalue(tql1)"); REPORT Real eps = FloatingPointPrecision::Epsilon(); int n = D.Nrows(); int l; for (l=1; l=l; i--) { Real ei = E.element(i); Real di = D.element(i); Real& ei1 = E.element(i+1); g = c * ei; h = c * p; if ( fabs(p) >= fabs(ei)) { REPORT c = ei / p; r = sqrt(c*c + 1.0); ei1 = s*p*r; s = c/r; c = 1.0/r; } else { REPORT c = p / ei; r = sqrt(c*c + 1.0); ei1 = s * ei * r; s = 1.0/r; c /= r; } p = c * di - s*g; D.element(i+1) = h + s * (c*g + s*di); } el = s*p; dl = c*p; if (fabs(el) <= b) { REPORT test = true; break; } } if (!test) Throw ( ConvergenceException(D) ); Real p = dl + f; test = false; for (i=l; i>0; i--) { if (p < D.element(i-1)) { REPORT D.element(i) = D.element(i-1); } else { REPORT test = true; break; } } if (!test) i=0; D.element(i) = p; } } void EigenValues(const SymmetricMatrix& A, DiagonalMatrix& D, Matrix& Z) { REPORT DiagonalMatrix E; tred2(A, D, E, Z); tql2(D, E, Z); SortSV(D,Z,true); } void EigenValues(const SymmetricMatrix& X, DiagonalMatrix& D) { REPORT DiagonalMatrix E; SymmetricMatrix A; tred3(X,D,E,A); tql1(D,E); } void EigenValues(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A) { REPORT DiagonalMatrix E; tred3(X,D,E,A); tql1(D,E); } #ifdef use_namespace } #endif newmat-1.10.4/example.cpp0000644001161000116100000002746410406436653013457 0ustar rzrrzr//$$ example.cpp Example of use of matrix package #define WANT_STREAM // include.h will get stream fns #define WANT_MATH // include.h will get math fns // newmatap.h will get include.h #include "newmatap.h" // need matrix applications #include "newmatio.h" // need matrix output routines #ifdef use_namespace using namespace NEWMAT; // access NEWMAT namespace #endif // demonstration of matrix package on linear regression problem void test1(Real* y, Real* x1, Real* x2, int nobs, int npred) { cout << "\n\nTest 1 - traditional, bad\n"; // traditional sum of squares and products method of calculation // but not adjusting means; maybe subject to round-off error // make matrix of predictor values with 1s into col 1 of matrix int npred1 = npred+1; // number of cols including col of ones. Matrix X(nobs,npred1); X.Column(1) = 1.0; // load x1 and x2 into X // [use << rather than = when loading arrays] X.Column(2) << x1; X.Column(3) << x2; // vector of Y values ColumnVector Y(nobs); Y << y; // form sum of squares and product matrix // [use << rather than = for copying Matrix into SymmetricMatrix] SymmetricMatrix SSQ; SSQ << X.t() * X; // calculate estimate // [bracket last two terms to force this multiplication first] // [ .i() means inverse, but inverse is not explicity calculated] ColumnVector A = SSQ.i() * (X.t() * Y); // Get variances of estimates from diagonal elements of inverse of SSQ // get inverse of SSQ - we need it for finding D DiagonalMatrix D; D << SSQ.i(); ColumnVector V = D.AsColumn(); // Calculate fitted values and residuals ColumnVector Fitted = X * A; ColumnVector Residual = Y - Fitted; Real ResVar = Residual.SumSquare() / (nobs-npred1); // Get diagonals of Hat matrix (an expensive way of doing this) DiagonalMatrix Hat; Hat << X * (X.t() * X).i() * X.t(); // print out answers cout << "\nEstimates and their standard errors\n\n"; // make vector of standard errors ColumnVector SE(npred1); for (int i=1; i<=npred1; i++) SE(i) = sqrt(V(i)*ResVar); // use concatenation function to form matrix and use matrix print // to get two columns cout << setw(11) << setprecision(5) << (A | SE) << endl; cout << "\nObservations, fitted value, residual value, hat value\n"; // use concatenation again; select only columns 2 to 3 of X cout << setw(9) << setprecision(3) << (X.Columns(2,3) | Y | Fitted | Residual | Hat.AsColumn()); cout << "\n\n"; } void test2(Real* y, Real* x1, Real* x2, int nobs, int npred) { cout << "\n\nTest 2 - traditional, OK\n"; // traditional sum of squares and products method of calculation // with subtraction of means - less subject to round-off error // than test1 // make matrix of predictor values Matrix X(nobs,npred); // load x1 and x2 into X // [use << rather than = when loading arrays] X.Column(1) << x1; X.Column(2) << x2; // vector of Y values ColumnVector Y(nobs); Y << y; // make vector of 1s ColumnVector Ones(nobs); Ones = 1.0; // calculate means (averages) of x1 and x2 [ .t() takes transpose] RowVector M = Ones.t() * X / nobs; // and subtract means from x1 and x1 Matrix XC(nobs,npred); XC = X - Ones * M; // do the same to Y [use Sum to get sum of elements] ColumnVector YC(nobs); Real m = Sum(Y) / nobs; YC = Y - Ones * m; // form sum of squares and product matrix // [use << rather than = for copying Matrix into SymmetricMatrix] SymmetricMatrix SSQ; SSQ << XC.t() * XC; // calculate estimate // [bracket last two terms to force this multiplication first] // [ .i() means inverse, but inverse is not explicity calculated] ColumnVector A = SSQ.i() * (XC.t() * YC); // calculate estimate of constant term // [AsScalar converts 1x1 matrix to Real] Real a = m - (M * A).AsScalar(); // Get variances of estimates from diagonal elements of inverse of SSQ // [ we are taking inverse of SSQ - we need it for finding D ] Matrix ISSQ = SSQ.i(); DiagonalMatrix D; D << ISSQ; ColumnVector V = D.AsColumn(); Real v = 1.0/nobs + (M * ISSQ * M.t()).AsScalar(); // for calc variance of const // Calculate fitted values and residuals int npred1 = npred+1; ColumnVector Fitted = X * A + a; ColumnVector Residual = Y - Fitted; Real ResVar = Residual.SumSquare() / (nobs-npred1); // Get diagonals of Hat matrix (an expensive way of doing this) Matrix X1(nobs,npred1); X1.Column(1)<0 && alpha1>0 && beta1>0 && (alpha1+beta1)<1.0; } Real GARCH11_LL::LogLikelihood() { // cout << endl << " "; // cout << setw(10) << setprecision(5) << beta; // cout << setw(10) << setprecision(5) << alpha0; // cout << setw(10) << setprecision(5) << alpha1; // cout << setw(10) << setprecision(5) << beta1; // cout << endl; ColumnVector H(n); // residual variances ColumnVector U = Y - X * beta; // the residuals ColumnVector LH(n); // derivative of log-likelihood wrt H // each row corresponds to one observation LH(1)=0; Matrix Hderiv(n,4); // rectangular matrix of derivatives // of H wrt parameters // each row corresponds to one observation // each column to one of the parameters // Regard Y(1) as fixed and don't include in likelihood // then put in an expected value of H(1) in place of actual value // which we don't know. Use // E{H(i)} = alpha0 + alpha1 * E{square(epsilon(i-1))} + beta1 * E{H(i-1)} // and E{square(epsilon(i-1))} = E{H(i-1)} = E{H(i)} Real denom = (1-alpha1-beta1); H(1) = alpha0/denom; // the expected value of H Hderiv(1,1) = 0; Hderiv(1,2) = 1.0 / denom; Hderiv(1,3) = alpha0 / square(denom); Hderiv(1,4) = Hderiv(1,3); Real LL = 0.0; // the log likelihood Real sum1 = 0; // for forming derivative wrt beta Real sum2 = 0; // for forming second derivative wrt beta for (int i=2; i<=n; i++) { Real u1 = U(i-1); Real h1 = H(i-1); Real h = alpha0 + alpha1*square(u1) + beta1*h1; // variance of this obsv. H(i) = h; Real u = U(i); LL += log(h) + square(u) / h; // -2 * log likelihood // Hderiv are derivatives of h with respect to the parameters // need to allow for h1 depending on parameters Hderiv(i,1) = -2*u1*alpha1*X(i-1) + beta1*Hderiv(i-1,1); // beta Hderiv(i,2) = 1 + beta1*Hderiv(i-1,2); // alpha0 Hderiv(i,3) = square(u1) + beta1*Hderiv(i-1,3); // alpha1 Hderiv(i,4) = h1 + beta1*Hderiv(i-1,4); // beta1 LH(i) = -0.5 * (1/h - square(u/h)); sum1 += u * X(i)/ h; sum2 += square(X(i)) / h; } D = Hderiv.t()*LH; // derivatives of likelihood wrt parameters D(1) += sum1; // add on deriv wrt beta from square(u) term // cout << setw(10) << setprecision(5) << D << endl; // do minus expected value of second derivatives if (wg) // do only if second derivatives wanted { Hderiv.Row(1) = 0.0; Hderiv = H.AsDiagonal().i() * Hderiv; D2 << Hderiv.t() * Hderiv; D2 = D2 / 2.0; D2(1,1) += sum2; // cout << setw(10) << setprecision(5) << D2 << endl; // DiagonalMatrix DX; EigenValues(D2,DX); // cout << setw(10) << setprecision(5) << DX << endl; } return -0.5 * LL; } ReturnMatrix GARCH11_LL::Derivatives() { return D; } ReturnMatrix GARCH11_LL::FI() { if (!wg) cout << endl << "unexpected call of FI" << endl; return D2; } int main() { // get data ifstream fin("garch.dat"); if (!fin) { cout << "cannot find garch.dat\n"; exit(1); } int n; fin >> n; // series length // Y contains the dependant variable, X the predictor variable ColumnVector Y(n), X(n); int i; for (i=1; i<=n; i++) fin >> Y(i) >> X(i); cout << "Read " << n << " data points - begin fit\n\n"; // now do the fit ColumnVector H(n); GARCH11_LL garch11(Y,X); // loglikehood "object" MLE_D_FI mle_d_fi(garch11,100,0.0001); // mle "object" ColumnVector Para(4); // to hold the parameters Para << 0.0 << 0.1 << 0.1 << 0.1; // starting values // (Should change starting values to a more intelligent formula) mle_d_fi.Fit(Para); // do the fit ColumnVector SE; mle_d_fi.GetStandardErrors(SE); cout << "\n\n"; cout << "estimates and standard errors\n"; cout << setw(15) << setprecision(5) << (Para | SE) << endl << endl; SymmetricMatrix Corr; mle_d_fi.GetCorrelations(Corr); cout << "correlation matrix\n"; cout << setw(10) << setprecision(2) << Corr << endl << endl; cout << "inverse of correlation matrix\n"; cout << setw(10) << setprecision(2) << Corr.i() << endl << endl; return 0; } newmat-1.10.4/garch.dat0000644001161000116100000002636106070225150013057 0ustar rzrrzr500 3.44443 -0.49800 1.43549 -0.49600 3.70477 -0.49400 -3.82558 -0.49200 1.20130 -0.49000 -2.62383 -0.48800 -1.34321 -0.48600 -0.35801 -0.48400 -2.18813 -0.48200 -1.98628 -0.48000 -1.53262 -0.47800 -1.45007 -0.47600 -1.18593 -0.47400 -0.55274 -0.47200 -1.55943 -0.47000 -3.10084 -0.46800 0.44254 -0.46600 -0.63936 -0.46400 2.44989 -0.46200 -2.14392 -0.46000 0.47310 -0.45800 -1.64464 -0.45600 0.56628 -0.45400 -0.80925 -0.45200 -0.78961 -0.45000 -1.12984 -0.44800 -0.50715 -0.44600 -1.75134 -0.44400 -1.04231 -0.44200 0.94435 -0.44000 1.16306 -0.43800 -2.87888 -0.43600 -3.31084 -0.43400 -3.06191 -0.43200 1.06977 -0.43000 3.50462 -0.42800 3.94848 -0.42600 1.56565 -0.42400 -5.21742 -0.42200 1.94652 -0.42000 -3.01182 -0.41800 -3.88963 -0.41600 -0.31319 -0.41400 -5.71752 -0.41200 -6.72218 -0.41000 3.23482 -0.40800 2.12675 -0.40600 -0.10975 -0.40400 -1.73790 -0.40200 -0.86870 -0.40000 -1.46022 -0.39800 -0.22960 -0.39600 0.01596 -0.39400 0.00568 -0.39200 -3.41221 -0.39000 -0.47401 -0.38800 -1.76305 -0.38600 -0.49640 -0.38400 -2.36184 -0.38200 -0.09625 -0.38000 -2.81448 -0.37800 3.14301 -0.37600 1.88025 -0.37400 -2.61618 -0.37200 -1.56239 -0.37000 0.95722 -0.36800 1.29773 -0.36600 -1.45155 -0.36400 -0.63342 -0.36200 -0.78925 -0.36000 0.42473 -0.35800 1.39599 -0.35600 1.03934 -0.35400 -0.11042 -0.35200 0.89123 -0.35000 0.93411 -0.34800 2.78027 -0.34600 3.37402 -0.34400 -0.07986 -0.34200 0.79142 -0.34000 -4.17148 -0.33800 -1.26717 -0.33600 -4.36262 -0.33400 1.17431 -0.33200 -1.75656 -0.33000 0.40495 -0.32800 0.17572 -0.32600 -0.27991 -0.32400 -0.85524 -0.32200 -1.23380 -0.32000 -1.01889 -0.31800 1.08393 -0.31600 -0.55989 -0.31400 -1.91643 -0.31200 -1.23897 -0.31000 -0.85407 -0.30800 0.35218 -0.30600 -1.57057 -0.30400 0.20665 -0.30200 0.19680 -0.30000 0.03116 -0.29800 0.09100 -0.29600 1.03416 -0.29400 -0.16048 -0.29200 -0.27530 -0.29000 -0.11056 -0.28800 -2.11332 -0.28600 -0.51348 -0.28400 -0.16360 -0.28200 1.30712 -0.28000 -0.94392 -0.27800 -0.06838 -0.27600 -0.04095 -0.27400 -2.00364 -0.27200 0.63950 -0.27000 -1.02895 -0.26800 -0.17454 -0.26600 -0.86659 -0.26400 0.81698 -0.26200 0.51579 -0.26000 -0.74525 -0.25800 2.43378 -0.25600 0.89364 -0.25400 1.81727 -0.25200 -0.29667 -0.25000 -0.99628 -0.24800 0.09452 -0.24600 1.73730 -0.24400 0.36819 -0.24200 -1.56521 -0.24000 0.74916 -0.23800 0.56802 -0.23600 -1.34157 -0.23400 -0.65638 -0.23200 -2.12183 -0.23000 -2.35486 -0.22800 -2.09369 -0.22600 -3.30745 -0.22400 -4.14763 -0.22200 -3.56306 -0.22000 0.78907 -0.21800 -3.74014 -0.21600 -2.73770 -0.21400 -4.43153 -0.21200 -0.80243 -0.21000 -0.17474 -0.20800 -0.38250 -0.20600 -0.98962 -0.20400 -1.41965 -0.20200 0.90585 -0.20000 0.66850 -0.19800 -0.81629 -0.19600 -3.04422 -0.19400 -0.94514 -0.19200 0.05209 -0.19000 0.21315 -0.18800 -0.86960 -0.18600 -1.72978 -0.18400 -2.85623 -0.18200 -3.15650 -0.18000 -0.09176 -0.17800 -1.27376 -0.17600 -1.06533 -0.17400 1.21766 -0.17200 0.41706 -0.17000 -0.30885 -0.16800 0.78344 -0.16600 -1.76348 -0.16400 2.46496 -0.16200 -0.32712 -0.16000 1.38586 -0.15800 0.33513 -0.15600 0.66116 -0.15400 0.92420 -0.15200 -0.67200 -0.15000 -0.90707 -0.14800 -0.41053 -0.14600 0.62288 -0.14400 0.78497 -0.14200 0.99670 -0.14000 -2.19972 -0.13800 0.21922 -0.13600 -0.15003 -0.13400 -0.72706 -0.13200 0.13596 -0.13000 -0.00235 -0.12800 0.50025 -0.12600 0.80875 -0.12400 -0.71010 -0.12200 -3.85477 -0.12000 2.45549 -0.11800 -2.87772 -0.11600 1.03987 -0.11400 -1.41914 -0.11200 -1.87414 -0.11000 1.32656 -0.10800 2.15281 -0.10600 3.25624 -0.10400 -3.72420 -0.10200 -4.01675 -0.10000 1.19241 -0.09800 0.35189 -0.09600 -0.40223 -0.09400 0.84146 -0.09200 1.08746 -0.09000 2.20874 -0.08800 -0.18822 -0.08600 -1.29757 -0.08400 -1.36022 -0.08200 0.54575 -0.08000 -0.23008 -0.07800 0.00750 -0.07600 1.81600 -0.07400 -0.07319 -0.07200 0.70587 -0.07000 -2.67033 -0.06800 0.67446 -0.06600 -0.21002 -0.06400 2.11396 -0.06200 -0.94189 -0.06000 0.27803 -0.05800 -0.92172 -0.05600 1.37776 -0.05400 2.72565 -0.05200 0.47208 -0.05000 -3.33845 -0.04800 -0.20695 -0.04600 -2.18905 -0.04400 -4.33413 -0.04200 0.17860 -0.04000 -5.57817 -0.03800 -0.32771 -0.03600 1.47321 -0.03400 2.33767 -0.03200 1.22282 -0.03000 -1.48593 -0.02800 0.79435 -0.02600 0.54491 -0.02400 1.31706 -0.02200 -1.26472 -0.02000 -1.72634 -0.01800 -3.85299 -0.01600 0.43717 -0.01400 -3.39362 -0.01200 -3.60823 -0.01000 0.18868 -0.00800 1.23035 -0.00600 1.70454 -0.00400 -1.44766 -0.00200 0.99808 0.00000 0.24554 0.00200 1.44446 0.00400 0.96697 0.00600 -3.30396 0.00800 -5.97223 0.01000 1.22379 0.01200 6.00662 0.01400 4.43380 0.01600 2.01081 0.01800 -2.74552 0.02000 1.19452 0.02200 3.81020 0.02400 2.04597 0.02600 0.66764 0.02800 2.68350 0.03000 -2.85514 0.03200 0.21727 0.03400 1.88780 0.03600 2.23549 0.03800 1.57589 0.04000 1.92344 0.04200 -1.78414 0.04400 -0.67367 0.04600 0.19357 0.04800 1.00246 0.05000 2.13782 0.05200 1.90734 0.05400 0.43943 0.05600 -0.55699 0.05800 1.76985 0.06000 -0.77310 0.06200 -0.33812 0.06400 -0.85572 0.06600 -2.49390 0.06800 -3.17954 0.07000 2.86688 0.07200 2.03589 0.07400 -1.34393 0.07600 1.01839 0.07800 -0.15220 0.08000 1.17978 0.08200 1.96847 0.08400 1.90596 0.08600 3.72675 0.08800 -0.65513 0.09000 -1.45672 0.09200 -0.08779 0.09400 -0.39105 0.09600 1.88645 0.09800 2.34710 0.10000 -2.65900 0.10200 -0.47996 0.10400 -2.51512 0.10600 -3.59097 0.10800 -1.62117 0.11000 -2.43947 0.11200 3.50339 0.11400 3.05144 0.11600 -2.73565 0.11800 -1.31556 0.12000 1.85250 0.12200 -1.03864 0.12400 0.79097 0.12600 -0.12426 0.12800 0.48964 0.13000 1.42419 0.13200 0.55098 0.13400 -0.78121 0.13600 -0.01716 0.13800 -1.27952 0.14000 1.91981 0.14200 0.25822 0.14400 0.68516 0.14600 1.25616 0.14800 -1.40178 0.15000 -0.99551 0.15200 1.45728 0.15400 -1.66513 0.15600 -1.20284 0.15800 1.84775 0.16000 -1.91535 0.16200 0.34142 0.16400 1.90641 0.16600 1.55524 0.16800 1.77263 0.17000 1.25731 0.17200 -0.66331 0.17400 0.93506 0.17600 0.87120 0.17800 0.73840 0.18000 -1.48181 0.18200 -1.76043 0.18400 0.96176 0.18600 1.29128 0.18800 1.20889 0.19000 0.78386 0.19200 1.54668 0.19400 -0.25996 0.19600 0.93201 0.19800 1.30374 0.20000 2.23175 0.20200 -0.42525 0.20400 1.12784 0.20600 -0.42014 0.20800 -0.00577 0.21000 -1.14837 0.21200 2.48454 0.21400 -0.51466 0.21600 -0.06257 0.21800 -1.25993 0.22000 1.26623 0.22200 3.05099 0.22400 -1.84077 0.22600 -0.36058 0.22800 2.65788 0.23000 -0.17717 0.23200 1.68915 0.23400 -1.53406 0.23600 1.78097 0.23800 -1.24217 0.24000 -4.17466 0.24200 0.80433 0.24400 0.70856 0.24600 -0.96881 0.24800 0.87322 0.25000 -2.45936 0.25200 2.95677 0.25400 1.81628 0.25600 -0.85793 0.25800 1.02089 0.26000 -1.05425 0.26200 -0.29861 0.26400 1.69682 0.26600 1.07389 0.26800 0.22183 0.27000 1.72766 0.27200 -0.99746 0.27400 -2.14178 0.27600 -1.67924 0.27800 1.56520 0.28000 -0.86864 0.28200 2.65155 0.28400 -2.27166 0.28600 0.68310 0.28800 0.84102 0.29000 0.64604 0.29200 0.68712 0.29400 1.56297 0.29600 -0.68136 0.29800 1.25519 0.30000 -1.38612 0.30200 2.36320 0.30400 5.40128 0.30600 -1.14776 0.30800 -1.36081 0.31000 0.07679 0.31200 -0.17231 0.31400 1.19094 0.31600 0.09285 0.31800 -0.85191 0.32000 -0.43739 0.32200 -0.22950 0.32400 2.21298 0.32600 0.75045 0.32800 0.97489 0.33000 -0.62158 0.33200 1.10503 0.33400 0.36977 0.33600 -0.32894 0.33800 2.13729 0.34000 4.42019 0.34200 -2.80916 0.34400 2.28181 0.34600 2.59053 0.34800 -1.52891 0.35000 -1.35202 0.35200 1.27639 0.35400 0.28782 0.35600 0.83540 0.35800 -0.32867 0.36000 1.16891 0.36200 0.02511 0.36400 -0.71878 0.36600 0.69811 0.36800 1.29399 0.37000 0.86300 0.37200 -0.12139 0.37400 -0.28069 0.37600 3.07623 0.37800 -2.91737 0.38000 0.16709 0.38200 -1.60815 0.38400 0.02795 0.38600 1.19657 0.38800 0.04390 0.39000 0.95983 0.39200 -1.83683 0.39400 -1.69167 0.39600 3.15836 0.39800 2.24002 0.40000 0.45225 0.40200 1.35014 0.40400 -1.67177 0.40600 -0.97317 0.40800 4.20922 0.41000 -0.03983 0.41200 -0.35933 0.41400 -1.49772 0.41600 2.72900 0.41800 -2.61061 0.42000 -0.26581 0.42200 -4.30162 0.42400 -3.55225 0.42600 -5.60739 0.42800 2.26730 0.43000 -0.05568 0.43200 -0.14348 0.43400 -1.73015 0.43600 -1.01649 0.43800 -2.39568 0.44000 3.41626 0.44200 2.23817 0.44400 -1.02668 0.44600 3.18086 0.44800 0.71908 0.45000 -0.37826 0.45200 -0.39837 0.45400 0.50378 0.45600 0.38287 0.45800 2.95404 0.46000 -1.16143 0.46200 0.89913 0.46400 -0.82190 0.46600 1.30638 0.46800 0.89138 0.47000 0.85038 0.47200 -1.38925 0.47400 3.74026 0.47600 4.60999 0.47800 1.31364 0.48000 5.17183 0.48200 1.82162 0.48400 1.09830 0.48600 1.36666 0.48800 -0.09676 0.49000 0.74155 0.49200 1.21910 0.49400 1.20746 0.49600 0.82236 0.49800 1.54856 0.50000 newmat-1.10.4/garch.txt0000644001161000116100000000227107215546604013134 0ustar rzrrzrRead 500 data points - begin fit -2247.993783 25945.58733 -537.4533239 -554.5885614 -537.2164816 26.36266449 -520.7034774 -519.7069034 6.153112127 -516.7045383 -516.690955 1.394658892 -516.396412 -516.215149 0.1555724069 -516.1509657 -516.1486772 0.02342168856 -516.1420803 -516.1404735 0.002342030975 -516.1395282 -516.1394913 0.0003287516503 -516.1393961 -516.1393755 3.25631984e-05 Converged estimates and standard errors 1.56690 0.22311 0.80046 0.20274 0.45307 0.08428 0.34655 0.09081 correlation matrix 1.00 0.00 -0.02 0.01 0.00 1.00 0.21 -0.81 -0.02 0.21 1.00 -0.63 0.01 -0.81 -0.63 1.00 inverse of correlation matrix 1.00 0.03 0.04 0.04 0.03 4.77 2.28 5.28 0.04 2.28 2.73 3.55 0.04 5.28 3.55 7.48 newmat-1.10.4/hholder.cpp0000644001161000116100000001130307414434476013440 0ustar rzrrzr//$$ hholder.cpp QR decomposition // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH #include "include.h" #include "newmatap.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,16); ++ExeCount; } #else #define REPORT {} #endif /*************************** QR decompositions ***************************/ inline Real square(Real x) { return x*x; } void QRZT(Matrix& X, LowerTriangularMatrix& L) { REPORT Tracer et("QZT(1)"); int n = X.Ncols(); int s = X.Nrows(); L.ReSize(s); Real* xi = X.Store(); int k; for (int i=0; i= 3 #define _STANDARD_ // use standard library #define ios_format_flags ios::fmtflags #endif // for Intel C++ for Linux #if defined __ICC #define _STANDARD_ // use standard library #define ios_format_flags ios::fmtflags #endif // for Microsoft Visual C++ 7 and above (and Intel simulating these) #if defined _MSC_VER && _MSC_VER >= 1300 #define _STANDARD_ // use standard library #endif #ifdef _STANDARD_ // using standard library #include #if defined _MSC_VER && _MSC_VER == 1200 #include // for VC++6 #endif #ifdef WANT_STREAM #include #include #endif #ifdef WANT_MATH #include #endif #ifdef WANT_STRING #include #endif #ifdef WANT_TIME #include #endif #ifdef WANT_FSTREAM #include #endif using namespace std; #else #define DEFAULT_HEADER // use AT&T style header // if no other compiler is recognised #ifdef _MSC_VER // Microsoft #include // reactivate these statements to run under MSC version 7.0 // typedef int jmp_buf[9]; // extern "C" // { // int __cdecl setjmp(jmp_buf); // void __cdecl longjmp(jmp_buf, int); // } #ifdef WANT_STREAM #include #include #endif #ifdef WANT_MATH #include #include #endif #ifdef WANT_STRING #include #endif #ifdef WANT_TIME #include #endif #ifdef WANT_FSTREAM #include #endif #undef DEFAULT_HEADER #endif #ifdef __ZTC__ // Zortech #include #ifdef WANT_STREAM #include #include #define flush "" // not defined in iomanip? #endif #ifdef WANT_MATH #include #include #endif #ifdef WANT_STRING #include #endif #ifdef WANT_TIME #include #endif #ifdef WANT_FSTREAM #include #endif #undef DEFAULT_HEADER #endif #if defined __BCPLUSPLUS__ || defined __TURBOC__ // Borland or Turbo #include #ifdef WANT_STREAM #include #include #endif #ifdef WANT_MATH #include #include // Borland has both float and values // but values.h returns +INF for // MAXDOUBLE in BC5 #endif #ifdef WANT_STRING #include #endif #ifdef WANT_TIME #include #endif #ifdef WANT_FSTREAM #include #endif #undef DEFAULT_HEADER #endif #ifdef __GNUG__ // Gnu C++ #include #ifdef WANT_STREAM #include #include #endif #ifdef WANT_MATH #include #include #endif #ifdef WANT_STRING #include #endif #ifdef WANT_TIME #include #endif #ifdef WANT_FSTREAM #include #endif #undef DEFAULT_HEADER #endif #ifdef __WATCOMC__ // Watcom C/C++ #include #ifdef WANT_STREAM #include #include #endif #ifdef WANT_MATH #include #include #endif #ifdef WANT_STRING #include #endif #ifdef WANT_TIME #include #endif #ifdef WANT_FSTREAM #include #endif #undef DEFAULT_HEADER #endif #ifdef macintosh // MPW C++ on the Mac #include #ifdef WANT_STREAM #include #include #endif #ifdef WANT_MATH #include #include #endif #ifdef WANT_STRING #include #endif #ifdef WANT_TIME #include #endif #ifdef WANT_FSTREAM #include #endif #undef DEFAULT_HEADER #endif #ifdef use_float_h // use float.h for precision values #include #ifdef WANT_STREAM #include #include #endif #ifdef WANT_MATH #include #include #endif #ifdef WANT_STRING #include #endif #ifdef WANT_TIME #include #endif #ifdef WANT_FSTREAM #include #endif #undef DEFAULT_HEADER #endif #ifdef DEFAULT_HEADER // for example AT&T #define ATandT #include #ifdef WANT_STREAM #include #include #endif #ifdef WANT_MATH #include #define SystemV // use System V #include #endif #ifdef WANT_STRING #include #endif #ifdef WANT_TIME #include #endif #ifdef WANT_FSTREAM #include #endif #endif // DEFAULT_HEADER #endif // _STANDARD_ #ifdef use_namespace namespace RBD_COMMON { #endif #ifdef USING_FLOAT // set precision type to float typedef float Real; typedef double long_Real; #endif #ifdef USING_DOUBLE // set precision type to double typedef double Real; typedef long double long_Real; #endif // This is for (very old) compilers that do not have bool automatically defined #ifndef bool_LIB #define bool_LIB 0 class bool { int value; public: bool(const int b) { value = b ? 1 : 0; } bool(const void* b) { value = b ? 1 : 0; } bool() {} operator int() const { return value; } int operator!() const { return !value; } }; const bool true = 1; const bool false = 0; #endif #ifdef use_namespace } #endif #ifdef use_namespace namespace RBD_COMMON {} namespace RBD_LIBRARIES // access all my libraries { using namespace RBD_COMMON; } #endif #endif ///@} newmat-1.10.4/jacobi.cpp0000644001161000116100000000741707417721230013243 0ustar rzrrzr//$$jacobi.cpp jacobi eigenvalue analysis // Copyright (C) 1991,2,3,4: R B Davies //#define WANT_STREAM #define WANT_MATH #include "include.h" #include "newmatap.h" #include "precisio.h" #include "newmatrm.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,18); ++ExeCount; } #else #define REPORT {} #endif void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A, Matrix& V, bool eivec) { Real epsilon = FloatingPointPrecision::Epsilon(); Tracer et("Jacobi"); REPORT int n = X.Nrows(); DiagonalMatrix B(n), Z(n); D.ReSize(n); A = X; if (eivec) { REPORT V.ReSize(n,n); D = 1.0; V = D; } B << A; D = B; Z = 0.0; A.Inject(Z); bool converged = false; for (int i=1; i<=50; i++) { Real sm=0.0; Real* a = A.Store(); int p = A.Storage(); while (p--) sm += fabs(*a++); // have previously zeroed diags if (sm==0.0) { REPORT converged = true; break; } Real tresh = (i<4) ? 0.2 * sm / square(n) : 0.0; a = A.Store(); for (p = 0; p < n; p++) { Real* ap1 = a + (p*(p+1))/2; Real& zp = Z.element(p); Real& dp = D.element(p); for (int q = p+1; q < n; q++) { Real* ap = ap1; Real* aq = a + (q*(q+1))/2; Real& zq = Z.element(q); Real& dq = D.element(q); Real& apq = A.element(q,p); Real g = 100 * fabs(apq); Real adp = fabs(dp); Real adq = fabs(dq); if (i>4 && g < epsilon*adp && g < epsilon*adq) { REPORT apq = 0.0; } else if (fabs(apq) > tresh) { REPORT Real t; Real h = dq - dp; Real ah = fabs(h); if (g < epsilon*ah) { REPORT t = apq / h; } else { REPORT Real theta = 0.5 * h / apq; t = 1.0 / ( fabs(theta) + sqrt(1.0 + square(theta)) ); if (theta<0.0) { REPORT t = -t; } } Real c = 1.0 / sqrt(1.0 + square(t)); Real s = t * c; Real tau = s / (1.0 + c); h = t * apq; zp -= h; zq += h; dp -= h; dq += h; apq = 0.0; int j = p; while (j--) { g = *ap; h = *aq; *ap++ = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau); } int ip = p+1; j = q-ip; ap += ip++; aq++; while (j--) { g = *ap; h = *aq; *ap = g-s*(h+g*tau); *aq++ = h+s*(g-h*tau); ap += ip++; } if (q < n-1) // last loop is non-empty { int iq = q+1; j = n-iq; ap += ip++; aq += iq++; for (;;) { g = *ap; h = *aq; *ap = g-s*(h+g*tau); *aq = h+s*(g-h*tau); if (!(--j)) break; ap += ip++; aq += iq++; } } if (eivec) { REPORT RectMatrixCol VP(V,p); RectMatrixCol VQ(V,q); Rotate(VP, VQ, tau, s); } } } } B = B + Z; D = B; Z = 0.0; } if (!converged) Throw(ConvergenceException(X)); if (eivec) SortSV(D, V, true); else SortAscending(D); } void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D) { REPORT SymmetricMatrix A; Matrix V; Jacobi(X,D,A,V,false); } void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, SymmetricMatrix& A) { REPORT Matrix V; Jacobi(X,D,A,V,false); } void Jacobi(const SymmetricMatrix& X, DiagonalMatrix& D, Matrix& V) { REPORT SymmetricMatrix A; Jacobi(X,D,A,V,true); } #ifdef use_namespace } #endif newmat-1.10.4/myexcept.cpp0000644001161000116100000003222110301336017013630 0ustar rzrrzr/// \ingroup rbd_common ///@{ /// \file myexcept.cpp /// Exception handler. /// The low level classes for /// - my exception class hierarchy /// - the functions needed for my simulated exceptions /// - the Tracer mechanism /// - routines for checking whether new and delete calls are balanced /// // Copyright (C) 1993,4,6: R B Davies #define WANT_STREAM // include.h will get stream fns #define WANT_STRING #include "include.h" // include standard files #include "myexcept.h" // for exception handling #ifdef use_namespace namespace RBD_COMMON { #endif //#define REG_DEREG // for print out uses of new/delete //#define CLEAN_LIST // to print entries being added to // or deleted from cleanup list #ifdef SimulateExceptions void Throw() { for (Janitor* jan = JumpBase::jl->janitor; jan; jan = jan->NextJanitor) jan->CleanUp(); JumpItem* jx = JumpBase::jl->ji; // previous jumpbase; if ( !jx ) { Terminate(); } // jl was initial JumpItem JumpBase::jl = jx; // drop down a level; cannot be in front // of previous line Tracer::last = JumpBase::jl->trace; longjmp(JumpBase::jl->env, 1); } #endif // end of simulate exceptions unsigned long BaseException::Select; char* BaseException::what_error; int BaseException::SoFar; int BaseException::LastOne; BaseException::BaseException(const char* a_what) { Select++; SoFar = 0; if (!what_error) // make space for exception message { LastOne = 511; what_error = new char[512]; if (!what_error) // fail to make space { LastOne = 0; what_error = (char *)"No heap space for exception message\n"; } } AddMessage("\n\nAn exception has been thrown\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } void BaseException::AddMessage(const char* a_what) { if (a_what) { int l = strlen(a_what); int r = LastOne - SoFar; if (l < r) { strcpy(what_error+SoFar, a_what); SoFar += l; } else if (r > 0) { strncpy(what_error+SoFar, a_what, r); what_error[LastOne] = 0; SoFar = LastOne; } } } void BaseException::AddInt(int value) { bool negative; if (value == 0) { AddMessage("0"); return; } else if (value < 0) { value = -value; negative = true; } else negative = false; int n = 0; int v = value; // how many digits will we need? while (v > 0) { v /= 10; n++; } if (negative) n++; if (LastOne-SoFar < n) { AddMessage("***"); return; } SoFar += n; n = SoFar; what_error[n] = 0; while (value > 0) { int nv = value / 10; int rm = value - nv * 10; value = nv; what_error[--n] = (char)(rm + '0'); } if (negative) what_error[--n] = '-'; return; } void Tracer::PrintTrace() { cout << "\n"; for (Tracer* et = last; et; et=et->previous) cout << " * " << et->entry << "\n"; } void Tracer::AddTrace() { if (last) { BaseException::AddMessage("Trace: "); BaseException::AddMessage(last->entry); for (Tracer* et = last->previous; et; et=et->previous) { BaseException::AddMessage("; "); BaseException::AddMessage(et->entry); } BaseException::AddMessage(".\n"); } } #ifdef SimulateExceptions Janitor::Janitor() { if (do_not_link) { do_not_link = false; NextJanitor = 0; OnStack = false; #ifdef CLEAN_LIST cout << "Not added to clean-list " << (unsigned long)this << "\n"; #endif } else { OnStack = true; #ifdef CLEAN_LIST cout << "Add to clean-list " << (unsigned long)this << "\n"; #endif NextJanitor = JumpBase::jl->janitor; JumpBase::jl->janitor=this; } } Janitor::~Janitor() { // expect the item to be deleted to be first on list // but must be prepared to search list if (OnStack) { #ifdef CLEAN_LIST cout << "Delete from clean-list " << (unsigned long)this << "\n"; #endif Janitor* lastjan = JumpBase::jl->janitor; if (this == lastjan) JumpBase::jl->janitor = NextJanitor; else { for (Janitor* jan = lastjan->NextJanitor; jan; jan = lastjan->NextJanitor) { if (jan==this) { lastjan->NextJanitor = jan->NextJanitor; return; } lastjan=jan; } Throw(BaseException( "Cannot resolve memory linked list\nSee notes in myexcept.cpp for details\n" )); // This message occurs when a call to ~Janitor() occurs, apparently // without a corresponding call to Janitor(). This could happen if my // way of deciding whether a constructor is being called by new // fails. // It may happen if you are using my simulated exceptions and also have // your compiler s exceptions turned on. // It can also happen if you have a class derived from Janitor // which does not include a copy constructor [ eg X(const &X) ]. // Possibly also if delete is applied an object on the stack (ie not // called by new). Otherwise, it is a bug in myexcept or your compiler. // If you do not #define TEMPS_DESTROYED_QUICKLY you will get this // error with Microsoft C 7.0. There are probably situations where // you will get this when you do define TEMPS_DESTROYED_QUICKLY. This // is a bug in MSC. Beware of "operator" statements for defining // conversions; particularly for converting from a Base class to a // Derived class. // You may get away with simply deleting this error message and Throw // statement if you can not find a better way of overcoming the // problem. In any case please tell me if you get this error message, // particularly for compilers apart from Microsoft C 7.0. } } } JumpItem* JumpBase::jl; // will be set to zero jmp_buf JumpBase::env; bool Janitor::do_not_link; // will be set to false int JanitorInitializer::ref_count; JanitorInitializer::JanitorInitializer() { if (ref_count++ == 0) new JumpItem; // need JumpItem at head of list } #endif // end of SimulateExceptions Tracer* Tracer::last; // will be set to zero void Terminate() { cout << "\n\nThere has been an exception with no handler - exiting"; const char* what = BaseException::what(); if (what) cout << what << "\n"; exit(1); } #ifdef DO_FREE_CHECK // Routines for tracing whether new and delete calls are balanced FreeCheckLink::FreeCheckLink() : next(FreeCheck::next) { FreeCheck::next = this; } FCLClass::FCLClass(void* t, char* name) : ClassName(name) { ClassStore=t; } FCLRealArray::FCLRealArray(void* t, char* o, int s) : Operation(o), size(s) { ClassStore=t; } FCLIntArray::FCLIntArray(void* t, char* o, int s) : Operation(o), size(s) { ClassStore=t; } FreeCheckLink* FreeCheck::next; int FreeCheck::BadDelete; void FCLClass::Report() { cout << " " << ClassName << " " << (unsigned long)ClassStore << "\n"; } void FCLRealArray::Report() { cout << " " << Operation << " " << (unsigned long)ClassStore << " " << size << "\n"; } void FCLIntArray::Report() { cout << " " << Operation << " " << (unsigned long)ClassStore << " " << size << "\n"; } void FreeCheck::Register(void* t, char* name) { FCLClass* f = new FCLClass(t,name); if (!f) { cout << "Out of memory in FreeCheck\n"; exit(1); } #ifdef REG_DEREG cout << "Registering " << name << " " << (unsigned long)t << "\n"; #endif } void FreeCheck::RegisterR(void* t, char* o, int s) { FCLRealArray* f = new FCLRealArray(t,o,s); if (!f) { cout << "Out of memory in FreeCheck\n"; exit(1); } #ifdef REG_DEREG cout << o << " " << s << " " << (unsigned long)t << "\n"; #endif } void FreeCheck::RegisterI(void* t, char* o, int s) { FCLIntArray* f = new FCLIntArray(t,o,s); if (!f) { cout << "Out of memory in FreeCheck\n"; exit(1); } #ifdef REG_DEREG cout << o << " " << s << " " << (unsigned long)t << "\n"; #endif } void FreeCheck::DeRegister(void* t, char* name) { FreeCheckLink* last = 0; #ifdef REG_DEREG cout << "Deregistering " << name << " " << (unsigned long)t << "\n"; #endif for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) { if (fcl->ClassStore==t) { if (last) last->next = fcl->next; else next = fcl->next; delete fcl; return; } last = fcl; } cout << "\nRequest to delete non-existent object of class and location:\n"; cout << " " << name << " " << (unsigned long)t << "\n"; BadDelete++; Tracer::PrintTrace(); cout << "\n"; } void FreeCheck::DeRegisterR(void* t, char* o, int s) { FreeCheckLink* last = 0; #ifdef REG_DEREG cout << o << " " << s << " " << (unsigned long)t << "\n"; #endif for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) { if (fcl->ClassStore==t) { if (last) last->next = fcl->next; else next = fcl->next; if (s >= 0 && ((FCLRealArray*)fcl)->size != s) { cout << "\nArray sizes do not agree:\n"; cout << " " << o << " " << (unsigned long)t << " " << ((FCLRealArray*)fcl)->size << " " << s << "\n"; Tracer::PrintTrace(); cout << "\n"; } delete fcl; return; } last = fcl; } cout << "\nRequest to delete non-existent real array:\n"; cout << " " << o << " " << (unsigned long)t << " " << s << "\n"; BadDelete++; Tracer::PrintTrace(); cout << "\n"; } void FreeCheck::DeRegisterI(void* t, char* o, int s) { FreeCheckLink* last = 0; #ifdef REG_DEREG cout << o << " " << s << " " << (unsigned long)t << "\n"; #endif for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) { if (fcl->ClassStore==t) { if (last) last->next = fcl->next; else next = fcl->next; if (s >= 0 && ((FCLIntArray*)fcl)->size != s) { cout << "\nArray sizes do not agree:\n"; cout << " " << o << " " << (unsigned long)t << " " << ((FCLIntArray*)fcl)->size << " " << s << "\n"; Tracer::PrintTrace(); cout << "\n"; } delete fcl; return; } last = fcl; } cout << "\nRequest to delete non-existent int array:\n"; cout << " " << o << " " << (unsigned long)t << " " << s << "\n"; BadDelete++; Tracer::PrintTrace(); cout << "\n"; } void FreeCheck::Status() { if (next) { cout << "\nObjects of the following classes remain undeleted:\n"; for (FreeCheckLink* fcl = next; fcl; fcl = fcl->next) fcl->Report(); cout << "\n"; } else cout << "\nNo objects remain undeleted\n\n"; if (BadDelete) { cout << "\nThere were " << BadDelete << " requests to delete non-existent items\n\n"; } } #endif // end of DO_FREE_CHECK // derived exception bodies Logic_error::Logic_error(const char* a_what) : BaseException() { Select = BaseException::Select; AddMessage("Logic error:- "); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Runtime_error::Runtime_error(const char* a_what) : BaseException() { Select = BaseException::Select; AddMessage("Runtime error:- "); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Domain_error::Domain_error(const char* a_what) : Logic_error() { Select = BaseException::Select; AddMessage("domain error\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Invalid_argument::Invalid_argument(const char* a_what) : Logic_error() { Select = BaseException::Select; AddMessage("invalid argument\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Length_error::Length_error(const char* a_what) : Logic_error() { Select = BaseException::Select; AddMessage("length error\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Out_of_range::Out_of_range(const char* a_what) : Logic_error() { Select = BaseException::Select; AddMessage("out of range\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } //Bad_cast::Bad_cast(const char* a_what) : Logic_error() //{ // Select = BaseException::Select; // AddMessage("bad cast\n"); AddMessage(a_what); // if (a_what) Tracer::AddTrace(); //} //Bad_typeid::Bad_typeid(const char* a_what) : Logic_error() //{ // Select = BaseException::Select; // AddMessage("bad type id.\n"); AddMessage(a_what); // if (a_what) Tracer::AddTrace(); //} Range_error::Range_error(const char* a_what) : Runtime_error() { Select = BaseException::Select; AddMessage("range error\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Overflow_error::Overflow_error(const char* a_what) : Runtime_error() { Select = BaseException::Select; AddMessage("overflow error\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } Bad_alloc::Bad_alloc(const char* a_what) : BaseException() { Select = BaseException::Select; AddMessage("bad allocation\n"); AddMessage(a_what); if (a_what) Tracer::AddTrace(); } unsigned long Logic_error::Select; unsigned long Runtime_error::Select; unsigned long Domain_error::Select; unsigned long Invalid_argument::Select; unsigned long Length_error::Select; unsigned long Out_of_range::Select; //unsigned long Bad_cast::Select; //unsigned long Bad_typeid::Select; unsigned long Range_error::Select; unsigned long Overflow_error::Select; unsigned long Bad_alloc::Select; #ifdef use_namespace } #endif ///@} newmat-1.10.4/myexcept.h0000644001161000116100000002735110301336076013312 0ustar rzrrzr/// \ingroup rbd_common ///@{ /// \file myexcept.h /// Exception handler. /// The low level classes for /// - my exception class hierarchy /// - the functions needed for my simulated exceptions /// - the Tracer mechanism /// - routines for checking whether new and delete calls are balanced /// // A set of classes to simulate exceptions in C++ // // Partially copied from Carlos Vidal s article in the C users journal // September 1992, pp 19-28 // // Operations defined // Try { } // Throw ( exception object ) // ReThrow // Catch ( exception class ) { } // CatchAll { } // CatchAndThrow // // All catch lists must end with a CatchAll or CatchAndThrow statement // but not both. // // When exceptions are finally implemented replace Try, Throw(E), Rethrow, // Catch, CatchAll, CatchAndThrow by try, throw E, throw, catch, // catch(...), and {}. // // All exception classes must be derived from BaseException, have no // non-static variables and must include the statement // // static unsigned long Select; // // Any constructor in one of these exception classes must include // // Select = BaseException::Select; // // For each exceptions class, EX_1, some .cpp file must include // // unsigned long EX_1::Select; // #ifndef EXCEPTION_LIB #define EXCEPTION_LIB #include "include.h" #ifdef use_namespace namespace RBD_COMMON { #endif void Terminate(); //********** classes for setting up exceptions and reporting ************// class BaseException; class Tracer // linked list showing how { // we got here const char* entry; Tracer* previous; public: Tracer(const char*); ~Tracer(); void ReName(const char*); static void PrintTrace(); // for printing trace static void AddTrace(); // insert trace in exception record static Tracer* last; // points to Tracer list friend class BaseException; }; class BaseException // The base exception class { protected: static char* what_error; // error message static int SoFar; // no. characters already entered static int LastOne; // last location in error buffer public: static void AddMessage(const char* a_what); // messages about exception static void AddInt(int value); // integer to error message static unsigned long Select; // for identifying exception BaseException(const char* a_what = 0); static const char* what() { return what_error; } // for getting error message }; #ifdef TypeDefException typedef BaseException Exception; // for compatibility with my older libraries #endif inline Tracer::Tracer(const char* e) : entry(e), previous(last) { last = this; } inline Tracer::~Tracer() { last = previous; } inline void Tracer::ReName(const char* e) { entry=e; } #ifdef SimulateExceptions // SimulateExceptions #include //************* the definitions of Try, Throw and Catch *****************// class JumpItem; class Janitor; class JumpBase // pointer to a linked list of jmp_buf s { public: static JumpItem *jl; static jmp_buf env; }; class JumpItem // an item in a linked list of jmp_buf s { public: JumpItem *ji; jmp_buf env; Tracer* trace; // to keep check on Tracer items Janitor* janitor; // list of items for cleanup JumpItem() : ji(JumpBase::jl), trace(0), janitor(0) { JumpBase::jl = this; } ~JumpItem() { JumpBase::jl = ji; } }; void Throw(); inline void Throw(const BaseException&) { Throw(); } #define Try \ if (!setjmp( JumpBase::jl->env )) { \ JumpBase::jl->trace = Tracer::last; \ JumpItem JI387256156; #define ReThrow Throw() #define Catch(EXCEPTION) \ } else if (BaseException::Select == EXCEPTION::Select) { #define CatchAll } else #define CatchAndThrow } else Throw(); //****************** cleanup heap following Throw ***********************// class Janitor { protected: static bool do_not_link; // set when new is called bool OnStack; // false if created by new public: Janitor* NextJanitor; virtual void CleanUp() {} Janitor(); virtual ~Janitor(); }; // The tiresome old trick for initializing the Janitor class // this is needed for classes derived from Janitor which have objects // declared globally class JanitorInitializer { public: JanitorInitializer(); private: static int ref_count; }; static JanitorInitializer JanInit; #endif // end of SimulateExceptions #ifdef UseExceptions #define Try try #define Throw(E) throw E #define ReThrow throw #define Catch catch #define CatchAll catch(...) #define CatchAndThrow {} #endif // end of UseExceptions #ifdef DisableExceptions // Disable exceptions #define Try { #define ReThrow Throw() #define Catch(EXCEPTION) } if (false) { #define CatchAll } if (false) #define CatchAndThrow } inline void Throw() { Terminate(); } inline void Throw(const BaseException&) { Terminate(); } #endif // end of DisableExceptions #ifndef SimulateExceptions // ! SimulateExceptions class Janitor // a dummy version { public: virtual void CleanUp() {} Janitor() {} virtual ~Janitor() {} }; #endif // end of ! SimulateExceptions //******************** FREE_CHECK and NEW_DELETE ***********************// #ifdef DO_FREE_CHECK // DO_FREE_CHECK // Routines for tracing whether new and delete calls are balanced class FreeCheck; class FreeCheckLink { protected: FreeCheckLink* next; void* ClassStore; FreeCheckLink(); virtual void Report()=0; // print details of link friend class FreeCheck; }; class FCLClass : public FreeCheckLink // for registering objects { char* ClassName; FCLClass(void* t, char* name); void Report(); friend class FreeCheck; }; class FCLRealArray : public FreeCheckLink // for registering real arrays { char* Operation; int size; FCLRealArray(void* t, char* o, int s); void Report(); friend class FreeCheck; }; class FCLIntArray : public FreeCheckLink // for registering int arrays { char* Operation; int size; FCLIntArray(void* t, char* o, int s); void Report(); friend class FreeCheck; }; class FreeCheck { static FreeCheckLink* next; static int BadDelete; public: static void Register(void*, char*); static void DeRegister(void*, char*); static void RegisterR(void*, char*, int); static void DeRegisterR(void*, char*, int); static void RegisterI(void*, char*, int); static void DeRegisterI(void*, char*, int); static void Status(); friend class FreeCheckLink; friend class FCLClass; friend class FCLRealArray; friend class FCLIntArray; }; #define FREE_CHECK(Class) \ public: \ void* operator new(size_t size) \ { \ void* t = ::operator new(size); FreeCheck::Register(t,#Class); \ return t; \ } \ void operator delete(void* t) \ { FreeCheck::DeRegister(t,#Class); ::operator delete(t); } #ifdef SimulateExceptions // SimulateExceptions #define NEW_DELETE(Class) \ public: \ void* operator new(size_t size) \ { \ do_not_link=true; \ void* t = ::operator new(size); FreeCheck::Register(t,#Class); \ return t; \ } \ void operator delete(void* t) \ { FreeCheck::DeRegister(t,#Class); ::operator delete(t); } #endif // end of SimulateExceptions #define MONITOR_REAL_NEW(Operation, Size, Pointer) \ FreeCheck::RegisterR(Pointer, Operation, Size); #define MONITOR_INT_NEW(Operation, Size, Pointer) \ FreeCheck::RegisterI(Pointer, Operation, Size); #define MONITOR_REAL_DELETE(Operation, Size, Pointer) \ FreeCheck::DeRegisterR(Pointer, Operation, Size); #define MONITOR_INT_DELETE(Operation, Size, Pointer) \ FreeCheck::DeRegisterI(Pointer, Operation, Size); #else // DO_FREE_CHECK not defined #define FREE_CHECK(Class) public: #define MONITOR_REAL_NEW(Operation, Size, Pointer) {} #define MONITOR_INT_NEW(Operation, Size, Pointer) {} #define MONITOR_REAL_DELETE(Operation, Size, Pointer) {} #define MONITOR_INT_DELETE(Operation, Size, Pointer) {} #ifdef SimulateExceptions // SimulateExceptions #define NEW_DELETE(Class) \ public: \ void* operator new(size_t size) \ { do_not_link=true; void* t = ::operator new(size); return t; } \ void operator delete(void* t) { ::operator delete(t); } #endif // end of SimulateExceptions #endif // end of ! DO_FREE_CHECK #ifndef SimulateExceptions // ! SimulateExceptions #define NEW_DELETE(Class) FREE_CHECK(Class) #endif // end of ! SimulateExceptions //********************* derived exceptions ******************************// class Logic_error : public BaseException { public: static unsigned long Select; Logic_error(const char* a_what = 0); }; class Runtime_error : public BaseException { public: static unsigned long Select; Runtime_error(const char* a_what = 0); }; class Domain_error : public Logic_error { public: static unsigned long Select; Domain_error(const char* a_what = 0); }; class Invalid_argument : public Logic_error { public: static unsigned long Select; Invalid_argument(const char* a_what = 0); }; class Length_error : public Logic_error { public: static unsigned long Select; Length_error(const char* a_what = 0); }; class Out_of_range : public Logic_error { public: static unsigned long Select; Out_of_range(const char* a_what = 0); }; //class Bad_cast : public Logic_error //{ //public: // static unsigned long Select; // Bad_cast(const char* a_what = 0); //}; //class Bad_typeid : public Logic_error //{ //public: // static unsigned long Select; // Bad_typeid(const char* a_what = 0); //}; class Range_error : public Runtime_error { public: static unsigned long Select; Range_error(const char* a_what = 0); }; class Overflow_error : public Runtime_error { public: static unsigned long Select; Overflow_error(const char* a_what = 0); }; class Bad_alloc : public BaseException { public: static unsigned long Select; Bad_alloc(const char* a_what = 0); }; #ifdef use_namespace } #endif #endif // end of EXCEPTION_LIB // body file: myexcept.cpp ///@} newmat-1.10.4/newfft.cpp0000644001161000116100000010323407417724526013312 0ustar rzrrzr//$ newfft.cpp // This is originally by Sande and Gentleman in 1967! I have translated from // Fortran into C and a little bit of C++. // It takes about twice as long as fftw // (http://theory.lcs.mit.edu/~fftw/homepage.html) // but is much shorter than fftw and so despite its age // might represent a reasonable // compromise between speed and complexity. // If you really need the speed get fftw. // THIS SUBROUTINE WAS WRITTEN BY G.SANDE OF PRINCETON UNIVERSITY AND // W.M.GENTLMAN OF THE BELL TELEPHONE LAB. IT WAS BROUGHT TO LONDON // BY DR. M.D. GODFREY AT THE IMPERIAL COLLEGE AND WAS ADAPTED FOR // BURROUGHS 6700 BY D. R. BRILLINGER AND J. PEMBERTON // IT REPRESENTS THE STATE OF THE ART OF COMPUTING COMPLETE FINITE // DISCRETE FOURIER TRANSFORMS AS OF NOV.1967. // OTHER PROGRAMS REQUIRED. // ONLY THOSE SUBROUTINES INCLUDED HERE. // USAGE. // CALL AR1DFT(N,X,Y) // WHERE N IS THE NUMBER OF POINTS IN THE SEQUENCE . // X - IS A ONE-DIMENSIONAL ARRAY CONTAINING THE REAL // PART OF THE SEQUENCE. // Y - IS A ONE-DIMENSIONAL ARRAY CONTAINING THE // IMAGINARY PART OF THE SEQUENCE. // THE TRANSFORM IS RETURNED IN X AND Y. // METHOD // FOR A GENERAL DISCUSSION OF THESE TRANSFORMS AND OF // THE FAST METHOD FOR COMPUTING THEM, SEE GENTLEMAN AND SANDE, // @FAST FOURIER TRANSFORMS - FOR FUN AND PROFIT,@ 1966 FALL JOINT // COMPUTER CONFERENCE. // THIS PROGRAM COMPUTES THIS FOR A COMPLEX SEQUENCE Z(T) OF LENGTH // N WHOSE ELEMENTS ARE STORED AT(X(I) , Y(I)) AND RETURNS THE // TRANSFORM COEFFICIENTS AT (X(I), Y(I)). // DESCRIPTION // AR1DFT IS A HIGHLY MODULAR ROUTINE CAPABLE OF COMPUTING IN PLACE // THE COMPLETE FINITE DISCRETE FOURIER TRANSFORM OF A ONE- // DIMENSIONAL SEQUENCE OF RATHER GENERAL LENGTH N. // THE MAIN ROUTINE , AR1DFT ITSELF, FACTORS N. IT THEN CALLS ON // ON GR 1D FT TO COMPUTE THE ACTUAL TRANSFORMS, USING THESE FACTORS. // THIS GR 1D FT DOES, CALLING AT EACH STAGE ON THE APPROPRIATE KERN // EL R2FTK, R4FTK, R8FTK, R16FTK, R3FTK, R5FTK, OR RPFTK TO PERFORM // THE COMPUTATIONS FOR THIS PASS OVER THE SEQUENCE, DEPENDING ON // WHETHER THE CORRESPONDING FACTOR IS 2, 4, 8, 16, 3, 5, OR SOME // MORE GENERAL PRIME P. WHEN GR1DFT IS FINISHED THE TRANSFORM IS // COMPUTED, HOWEVER, THE RESULTS ARE STORED IN "DIGITS REVERSED" // ORDER. AR1DFT THEREFORE, CALLS UPON GR 1S FS TO SORT THEM OUT. // TO RETURN TO THE FACTORIZATION, SINGLETON HAS POINTED OUT THAT // THE TRANSFORMS ARE MORE EFFICIENT IF THE SAMPLE SIZE N, IS OF THE // FORM B*A**2 AND B CONSISTS OF A SINGLE FACTOR. IN SUCH A CASE // IF WE PROCESS THE FACTORS IN THE ORDER ABA THEN // THE REORDERING CAN BE DONE AS FAST IN PLACE, AS WITH SCRATCH // STORAGE. BUT AS B BECOMES MORE COMPLICATED, THE COST OF THE DIGIT // REVERSING DUE TO B PART BECOMES VERY EXPENSIVE IF WE TRY TO DO IT // IN PLACE. IN SUCH A CASE IT MIGHT BE BETTER TO USE EXTRA STORAGE // A ROUTINE TO DO THIS IS, HOWEVER, NOT INCLUDED HERE. // ANOTHER FEATURE INFLUENCING THE FACTORIZATION IS THAT FOR ANY FIXED // FACTOR N WE CAN PREPARE A SPECIAL KERNEL WHICH WILL COMPUTE // THAT STAGE OF THE TRANSFORM MORE EFFICIENTLY THAN WOULD A KERNEL // FOR GENERAL FACTORS, ESPECIALLY IF THE GENERAL KERNEL HAD TO BE // APPLIED SEVERAL TIMES. FOR EXAMPLE, FACTORS OF 4 ARE MORE // EFFICIENT THAN FACTORS OF 2, FACTORS OF 8 MORE EFFICIENT THAN 4,ETC // ON THE OTHER HAND DIMINISHING RETURNS RAPIDLY SET IN, ESPECIALLY // SINCE THE LENGTH OF THE KERNEL FOR A SPECIAL CASE IS ROUGHLY // PROPORTIONAL TO THE FACTOR IT DEALS WITH. HENCE THESE PROBABLY ARE // ALL THE KERNELS WE WISH TO HAVE. // RESTRICTIONS. // AN UNFORTUNATE FEATURE OF THE SORTING PROBLEM IS THAT THE MOST // EFFICIENT WAY TO DO IT IS WITH NESTED DO LOOPS, ONE FOR EACH // FACTOR. THIS PUTS A RESTRICTION ON N AS TO HOW MANY FACTORS IT // CAN HAVE. CURRENTLY THE LIMIT IS 16, BUT THE LIMIT CAN BE READILY // RAISED IF NECESSARY. // A SECOND RESTRICTION OF THE PROGRAM IS THAT LOCAL STORAGE OF THE // THE ORDER P**2 IS REQUIRED BY THE GENERAL KERNEL RPFTK, SO SOME // LIMIT MUST BE SET ON P. CURRENTLY THIS IS 19, BUT IT CAN BE INCRE // INCREASED BY TRIVIAL CHANGES. // OTHER COMMENTS. //(1) THE ROUTINE IS ADAPTED TO CHECK WHETHER A GIVEN N WILL MEET THE // ABOVE FACTORING REQUIREMENTS AN, IF NOT, TO RETURN THE NEXT HIGHER // NUMBER, NX, SAY, WHICH WILL MEET THESE REQUIREMENTS. // THIS CAN BE ACCHIEVED BY A STATEMENT OF THE FORM // CALL FACTR(N,X,Y). // IF A DIFFERENT N, SAY NX, IS RETURNED THEN THE TRANSFORMS COULD BE // OBTAINED BY EXTENDING THE SIZE OF THE X-ARRAY AND Y-ARRAY TO NX, // AND SETTING X(I) = Y(I) = 0., FOR I = N+1, NX. //(2) IF THE SEQUENCE Z IS ONLY A REAL SEQUENCE, THEN THE IMAGINARY PART // Y(I)=0., THIS WILL RETURN THE COSINE TRANSFORM OF THE REAL SEQUENCE // IN X, AND THE SINE TRANSFORM IN Y. #define WANT_STREAM #define WANT_MATH #include "newmatap.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,20); ++ExeCount; } #else #define REPORT {} #endif inline Real square(Real x) { return x*x; } inline int square(int x) { return x*x; } static void GR_1D_FS (int PTS, int N_SYM, int N_UN_SYM, const SimpleIntArray& SYM, int P_SYM, const SimpleIntArray& UN_SYM, Real* X, Real* Y); static void GR_1D_FT (int N, int N_FACTOR, const SimpleIntArray& FACTOR, Real* X, Real* Y); static void R_P_FTK (int N, int M, int P, Real* X, Real* Y); static void R_2_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1); static void R_3_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2); static void R_4_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2, Real* X3, Real* Y3); static void R_5_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2, Real* X3, Real* Y3, Real* X4, Real* Y4); static void R_8_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2, Real* X3, Real* Y3, Real* X4, Real* Y4, Real* X5, Real* Y5, Real* X6, Real* Y6, Real* X7, Real* Y7); static void R_16_FTK (int N, int M, Real* X0, Real* Y0, Real* X1, Real* Y1, Real* X2, Real* Y2, Real* X3, Real* Y3, Real* X4, Real* Y4, Real* X5, Real* Y5, Real* X6, Real* Y6, Real* X7, Real* Y7, Real* X8, Real* Y8, Real* X9, Real* Y9, Real* X10, Real* Y10, Real* X11, Real* Y11, Real* X12, Real* Y12, Real* X13, Real* Y13, Real* X14, Real* Y14, Real* X15, Real* Y15); static int BitReverse(int x, int prod, int n, const SimpleIntArray& f); bool FFT_Controller::ar_1d_ft (int PTS, Real* X, Real *Y) { // ARBITRARY RADIX ONE DIMENSIONAL FOURIER TRANSFORM REPORT int F,J,N,NF,P,PMAX,P_SYM,P_TWO,Q,R,TWO_GRP; // NP is maximum number of squared factors allows PTS up to 2**32 at least // NQ is number of not-squared factors - increase if we increase PMAX const int NP = 16, NQ = 10; SimpleIntArray PP(NP), QQ(NQ); TWO_GRP=16; PMAX=19; // PMAX is the maximum factor size // TWO_GRP is the maximum power of 2 handled as a single factor // Doesn't take advantage of combining powers of 2 when calculating // number of factors if (PTS<=1) return true; N=PTS; P_SYM=1; F=2; P=0; Q=0; // P counts the number of squared factors // Q counts the number of the rest // R = 0 for no non-squared factors; 1 otherwise // FACTOR holds all the factors - non-squared ones in the middle // - length is 2*P+Q // SYM also holds all the factors but with the non-squared ones // multiplied together - length is 2*P+R // PP holds the values of the squared factors - length is P // QQ holds the values of the rest - length is Q // P_SYM holds the product of the squared factors // find the factors - load into PP and QQ while (N > 1) { bool fail = true; for (J=F; J<=PMAX; J++) if (N % J == 0) { fail = false; F=J; break; } if (fail || P >= NP || Q >= NQ) return false; // can't factor N /= F; if (N % F != 0) QQ[Q++] = F; else { N /= F; PP[P++] = F; P_SYM *= F; } } R = (Q == 0) ? 0 : 1; // R = 0 if no not-squared factors, 1 otherwise NF = 2*P + Q; SimpleIntArray FACTOR(NF + 1), SYM(2*P + R); FACTOR[NF] = 0; // we need this in the "combine powers of 2" // load into SYM and FACTOR for (J=0; J0) { REPORT for (J=0; J 0) { REPORT SimpleIntArray U(N_SYM); for(MultiRadixCounter MRC(N_SYM, SYM, U); !MRC.Finish(); ++MRC) { if (MRC.Swap()) { int P = MRC.Reverse(); int JJ = MRC.Counter(); Real T; T=X[JJ]; X[JJ]=X[P]; X[P]=T; T=Y[JJ]; Y[JJ]=Y[P]; Y[P]=T; } } } int J,JL,K,L,M,MS; // UN_SYM contains the non-squared factors // I have replaced the Sande-Gentleman code as it runs into // integer overflow problems // My code (and theirs) would be improved by using a bit array // as suggested by Van Loan if (N_UN_SYM==0) { REPORT return; } P_UN_SYM=PTS/square(P_SYM); JL=(P_UN_SYM-3)*P_SYM; MS=P_UN_SYM*P_SYM; for (J = P_SYM; J<=JL; J+=P_SYM) { K=J; do K = P_SYM * BitReverse(K / P_SYM, P_UN_SYM, N_UN_SYM, UN_SYM); while (K 1) { bool fail = true; for (int J = F; J <= PMAX; J++) if (N % J == 0) { fail = false; F=J; break; } if (fail || P >= NP || Q >= NQ) { REPORT return false; } N /= F; if (N % F != 0) Q++; else { N /= F; P++; } } return true; // can factorise } bool FFT_Controller::OnlyOldFFT; // static variable // **************************** multi radix counter ********************** MultiRadixCounter::MultiRadixCounter(int nx, const SimpleIntArray& rx, SimpleIntArray& vx) : Radix(rx), Value(vx), n(nx), reverse(0), product(1), counter(0), finish(false) { REPORT for (int k = 0; k < n; k++) { Value[k] = 0; product *= Radix[k]; } } void MultiRadixCounter::operator++() { REPORT counter++; int p = product; for (int k = 0; k < n; k++) { Value[k]++; int p1 = p / Radix[k]; reverse += p1; if (Value[k] == Radix[k]) { REPORT Value[k] = 0; reverse -= p; p = p1; } else { REPORT return; } } finish = true; } static int BitReverse(int x, int prod, int n, const SimpleIntArray& f) { // x = c[0]+f[0]*(c[1]+f[1]*(c[2]+... // return c[n-1]+f[n-1]*(c[n-2]+f[n-2]*(c[n-3]+... // prod is the product of the f[i] // n is the number of f[i] (don't assume f has the correct length) REPORT const int* d = f.Data() + n; int sum = 0; int q = 1; while (n--) { prod /= *(--d); int c = x / prod; x-= c * prod; sum += q * c; q *= *d; } return sum; } #ifdef use_namespace } #endif newmat-1.10.4/newmat.h0000644001161000116100000020305610413657531012753 0ustar rzrrzr//$$ newmat.h definition file for new version of matrix package // Copyright (C) 1991,2,3,4,7,2000,2002: R B Davies #ifndef NEWMAT_LIB #define NEWMAT_LIB 0 #include "include.h" #include "boolean.h" #include "myexcept.h" #ifdef use_namespace namespace NEWMAT { using namespace RBD_COMMON; } namespace RBD_LIBRARIES { using namespace NEWMAT; } namespace NEWMAT { #endif //#define DO_REPORT // to activate REPORT #ifdef NO_LONG_NAMES #define UpperTriangularMatrix UTMatrix #define LowerTriangularMatrix LTMatrix #define SymmetricMatrix SMatrix #define DiagonalMatrix DMatrix #define BandMatrix BMatrix #define UpperBandMatrix UBMatrix #define LowerBandMatrix LBMatrix #define SymmetricBandMatrix SBMatrix #define BandLUMatrix BLUMatrix #endif #ifndef TEMPS_DESTROYED_QUICKLY_R #define ReturnMatrix ReturnMatrixX #else #define ReturnMatrix ReturnMatrixX& #endif // ************************** general utilities ****************************/ class GeneralMatrix; void MatrixErrorNoSpace(void*); // no space handler class LogAndSign // Return from LogDeterminant function // - value of the log plus the sign (+, - or 0) { Real log_value; int sign; public: LogAndSign() { log_value=0.0; sign=1; } LogAndSign(Real); void operator*=(Real); void PowEq(int k); // raise to power of k void ChangeSign() { sign = -sign; } Real LogValue() const { return log_value; } int Sign() const { return sign; } Real Value() const; FREE_CHECK(LogAndSign) }; // the following class is for counting the number of times a piece of code // is executed. It is used for locating any code not executed by test // routines. Use turbo GREP locate all places this code is called and // check which ones are not accessed. // Somewhat implementation dependent as it relies on "cout" still being // present when ExeCounter objects are destructed. #ifdef DO_REPORT class ExeCounter { int line; // code line number int fileid; // file identifier long nexe; // number of executions static int nreports; // number of reports public: ExeCounter(int,int); void operator++() { nexe++; } ~ExeCounter(); // prints out reports }; #endif // ************************** class MatrixType *****************************/ // Is used for finding the type of a matrix resulting from the binary operations // +, -, * and identifying what conversions are permissible. // This class must be updated when new matrix types are added. class GeneralMatrix; // defined later class BaseMatrix; // defined later class MatrixInput; // defined later class MatrixType { public: enum Attribute { Valid = 1, Diagonal = 2, // order of these is important Symmetric = 4, Band = 8, Lower = 16, Upper = 32, LUDeco = 64, Ones = 128 }; enum { US = 0, UT = Valid + Upper, LT = Valid + Lower, Rt = Valid, Sm = Valid + Symmetric, Dg = Valid + Diagonal + Band + Lower + Upper + Symmetric, Id = Valid + Diagonal + Band + Lower + Upper + Symmetric + Ones, RV = Valid, // do not separate out CV = Valid, // vectors BM = Valid + Band, UB = Valid + Band + Upper, LB = Valid + Band + Lower, SB = Valid + Band + Symmetric, Ct = Valid + LUDeco, BC = Valid + Band + LUDeco }; static int nTypes() { return 10; } // number of different types // exclude Ct, US, BC public: int attribute; bool DataLossOK; // true if data loss is OK when // this represents a destination public: MatrixType () : DataLossOK(false) {} MatrixType (int i) : attribute(i), DataLossOK(false) {} MatrixType (int i, bool dlok) : attribute(i), DataLossOK(dlok) {} MatrixType (const MatrixType& mt) : attribute(mt.attribute), DataLossOK(mt.DataLossOK) {} void operator=(const MatrixType& mt) { attribute = mt.attribute; DataLossOK = mt.DataLossOK; } void SetDataLossOK() { DataLossOK = true; } int operator+() const { return attribute; } MatrixType operator+(MatrixType mt) const { return MatrixType(attribute & mt.attribute); } MatrixType operator*(const MatrixType&) const; MatrixType SP(const MatrixType&) const; MatrixType KP(const MatrixType&) const; MatrixType operator|(const MatrixType& mt) const { return MatrixType(attribute & mt.attribute & Valid); } MatrixType operator&(const MatrixType& mt) const { return MatrixType(attribute & mt.attribute & Valid); } bool operator>=(MatrixType mt) const { return ( attribute & mt.attribute ) == attribute; } bool operator<(MatrixType mt) const // for MS Visual C++ 4 { return ( attribute & mt.attribute ) != attribute; } bool operator==(MatrixType t) const { return (attribute == t.attribute); } bool operator!=(MatrixType t) const { return (attribute != t.attribute); } bool operator!() const { return (attribute & Valid) == 0; } MatrixType i() const; // type of inverse MatrixType t() const; // type of transpose MatrixType AddEqualEl() const // Add constant to matrix { return MatrixType(attribute & (Valid + Symmetric)); } MatrixType MultRHS() const; // type for rhs of multiply MatrixType sub() const // type of submatrix { return MatrixType(attribute & Valid); } MatrixType ssub() const // type of sym submatrix { return MatrixType(attribute); } // not for selection matrix GeneralMatrix* New() const; // new matrix of given type GeneralMatrix* New(int,int,BaseMatrix*) const; // new matrix of given type const char* Value() const; // to print type friend bool Rectangular(MatrixType a, MatrixType b, MatrixType c); friend bool Compare(const MatrixType&, MatrixType&); // compare and check conv. bool IsBand() const { return (attribute & Band) != 0; } bool IsDiagonal() const { return (attribute & Diagonal) != 0; } bool IsSymmetric() const { return (attribute & Symmetric) != 0; } bool CannotConvert() const { return (attribute & LUDeco) != 0; } // used by operator== FREE_CHECK(MatrixType) }; // *********************** class MatrixBandWidth ***********************/ class MatrixBandWidth { public: int lower; int upper; MatrixBandWidth(const int l, const int u) : lower(l), upper (u) {} MatrixBandWidth(const int i) : lower(i), upper(i) {} MatrixBandWidth operator+(const MatrixBandWidth&) const; MatrixBandWidth operator*(const MatrixBandWidth&) const; MatrixBandWidth minimum(const MatrixBandWidth&) const; MatrixBandWidth t() const { return MatrixBandWidth(upper,lower); } bool operator==(const MatrixBandWidth& bw) const { return (lower == bw.lower) && (upper == bw.upper); } bool operator!=(const MatrixBandWidth& bw) const { return !operator==(bw); } int Upper() const { return upper; } int Lower() const { return lower; } FREE_CHECK(MatrixBandWidth) }; // ********************* Array length specifier ************************/ // This class is introduced to avoid constructors such as // ColumnVector(int) // being used for conversions class ArrayLengthSpecifier { int value; public: int Value() const { return value; } ArrayLengthSpecifier(int l) : value(l) {} }; // ************************* Matrix routines ***************************/ class MatrixRowCol; // defined later class MatrixRow; class MatrixCol; class MatrixColX; class GeneralMatrix; // defined later class AddedMatrix; class MultipliedMatrix; class SubtractedMatrix; class SPMatrix; class KPMatrix; class ConcatenatedMatrix; class StackedMatrix; class SolvedMatrix; class ShiftedMatrix; class NegShiftedMatrix; class ScaledMatrix; class TransposedMatrix; class ReversedMatrix; class NegatedMatrix; class InvertedMatrix; class RowedMatrix; class ColedMatrix; class DiagedMatrix; class MatedMatrix; class GetSubMatrix; class ReturnMatrixX; class Matrix; class nricMatrix; class RowVector; class ColumnVector; class SymmetricMatrix; class UpperTriangularMatrix; class LowerTriangularMatrix; class DiagonalMatrix; class CroutMatrix; class BandMatrix; class LowerBandMatrix; class UpperBandMatrix; class SymmetricBandMatrix; class LinearEquationSolver; class GenericMatrix; #define MatrixTypeUnSp 0 //static MatrixType MatrixTypeUnSp(MatrixType::US); // // AT&T needs this class BaseMatrix : public Janitor // base of all matrix classes { protected: virtual int search(const BaseMatrix*) const = 0; // count number of times matrix // is referred to public: virtual GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp) = 0; // evaluate temporary // for old version of G++ // virtual GeneralMatrix* Evaluate(MatrixType mt) = 0; // GeneralMatrix* Evaluate() { return Evaluate(MatrixTypeUnSp); } #ifndef TEMPS_DESTROYED_QUICKLY AddedMatrix operator+(const BaseMatrix&) const; // results of operations MultipliedMatrix operator*(const BaseMatrix&) const; SubtractedMatrix operator-(const BaseMatrix&) const; ConcatenatedMatrix operator|(const BaseMatrix&) const; StackedMatrix operator&(const BaseMatrix&) const; ShiftedMatrix operator+(Real) const; ScaledMatrix operator*(Real) const; ScaledMatrix operator/(Real) const; ShiftedMatrix operator-(Real) const; TransposedMatrix t() const; // TransposedMatrix t; NegatedMatrix operator-() const; // change sign of elements ReversedMatrix Reverse() const; InvertedMatrix i() const; // InvertedMatrix i; RowedMatrix AsRow() const; ColedMatrix AsColumn() const; DiagedMatrix AsDiagonal() const; MatedMatrix AsMatrix(int,int) const; GetSubMatrix SubMatrix(int,int,int,int) const; GetSubMatrix SymSubMatrix(int,int) const; GetSubMatrix Row(int) const; GetSubMatrix Rows(int,int) const; GetSubMatrix Column(int) const; GetSubMatrix Columns(int,int) const; #else AddedMatrix& operator+(const BaseMatrix&) const; // results of operations MultipliedMatrix& operator*(const BaseMatrix&) const; SubtractedMatrix& operator-(const BaseMatrix&) const; ConcatenatedMatrix& operator|(const BaseMatrix&) const; StackedMatrix& operator&(const BaseMatrix&) const; ShiftedMatrix& operator+(Real) const; ScaledMatrix& operator*(Real) const; ScaledMatrix& operator/(Real) const; ShiftedMatrix& operator-(Real) const; TransposedMatrix& t() const; // TransposedMatrix& t; NegatedMatrix& operator-() const; // change sign of elements ReversedMatrix& Reverse() const; InvertedMatrix& i() const; // InvertedMatrix& i; RowedMatrix& AsRow() const; ColedMatrix& AsColumn() const; DiagedMatrix& AsDiagonal() const; MatedMatrix& AsMatrix(int,int) const; GetSubMatrix& SubMatrix(int,int,int,int) const; GetSubMatrix& SymSubMatrix(int,int) const; GetSubMatrix& Row(int) const; GetSubMatrix& Rows(int,int) const; GetSubMatrix& Column(int) const; GetSubMatrix& Columns(int,int) const; #endif Real AsScalar() const; // conversion of 1 x 1 matrix virtual LogAndSign LogDeterminant() const; Real Determinant() const; virtual Real SumSquare() const; Real NormFrobenius() const; virtual Real SumAbsoluteValue() const; virtual Real Sum() const; virtual Real MaximumAbsoluteValue() const; virtual Real MaximumAbsoluteValue1(int& i) const; virtual Real MaximumAbsoluteValue2(int& i, int& j) const; virtual Real MinimumAbsoluteValue() const; virtual Real MinimumAbsoluteValue1(int& i) const; virtual Real MinimumAbsoluteValue2(int& i, int& j) const; virtual Real Maximum() const; virtual Real Maximum1(int& i) const; virtual Real Maximum2(int& i, int& j) const; virtual Real Minimum() const; virtual Real Minimum1(int& i) const; virtual Real Minimum2(int& i, int& j) const; virtual Real Trace() const; Real Norm1() const; Real NormInfinity() const; virtual MatrixBandWidth BandWidth() const; // bandwidths of band matrix virtual void CleanUp() {} // to clear store void IEQND() const; // called by ineq. ops // virtual ReturnMatrix Reverse() const; // reverse order of elements //protected: // BaseMatrix() : t(this), i(this) {} friend class GeneralMatrix; friend class Matrix; friend class nricMatrix; friend class RowVector; friend class ColumnVector; friend class SymmetricMatrix; friend class UpperTriangularMatrix; friend class LowerTriangularMatrix; friend class DiagonalMatrix; friend class CroutMatrix; friend class BandMatrix; friend class LowerBandMatrix; friend class UpperBandMatrix; friend class SymmetricBandMatrix; friend class AddedMatrix; friend class MultipliedMatrix; friend class SubtractedMatrix; friend class SPMatrix; friend class KPMatrix; friend class ConcatenatedMatrix; friend class StackedMatrix; friend class SolvedMatrix; friend class ShiftedMatrix; friend class NegShiftedMatrix; friend class ScaledMatrix; friend class TransposedMatrix; friend class ReversedMatrix; friend class NegatedMatrix; friend class InvertedMatrix; friend class RowedMatrix; friend class ColedMatrix; friend class DiagedMatrix; friend class MatedMatrix; friend class GetSubMatrix; friend class ReturnMatrixX; friend class LinearEquationSolver; friend class GenericMatrix; NEW_DELETE(BaseMatrix) }; // ***************************** working classes **************************/ class GeneralMatrix : public BaseMatrix // declarable matrix types { virtual GeneralMatrix* Image() const; // copy of matrix protected: int tag; // shows whether can reuse int nrows, ncols; // dimensions int storage; // total store required Real* store; // point to store (0=not set) GeneralMatrix(); // initialise with no store GeneralMatrix(ArrayLengthSpecifier); // constructor getting store void Add(GeneralMatrix*, Real); // sum of GM and Real void Add(Real); // add Real to this void NegAdd(GeneralMatrix*, Real); // Real - GM void NegAdd(Real); // this = this - Real void Multiply(GeneralMatrix*, Real); // product of GM and Real void Multiply(Real); // multiply this by Real void Negate(GeneralMatrix*); // change sign void Negate(); // change sign void ReverseElements(); // internal reverse of elements void ReverseElements(GeneralMatrix*); // reverse order of elements void operator=(Real); // set matrix to constant Real* GetStore(); // get store or copy GeneralMatrix* BorrowStore(GeneralMatrix*, MatrixType); // temporarily access store void GetMatrix(const GeneralMatrix*); // used by = and initialise void Eq(const BaseMatrix&, MatrixType); // used by = void Eq(const BaseMatrix&, MatrixType, bool);// used by << void Eq2(const BaseMatrix&, MatrixType); // cut down version of Eq int search(const BaseMatrix*) const; virtual GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void CheckConversion(const BaseMatrix&); // check conversion OK void ReSize(int, int, int); // change dimensions virtual short SimpleAddOK(const GeneralMatrix* gm) { return 0; } // see bandmat.cpp for explanation public: GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); virtual MatrixType Type() const = 0; // type of a matrix int Nrows() const { return nrows; } // get dimensions int Ncols() const { return ncols; } int Storage() const { return storage; } Real* Store() const { return store; } virtual ~GeneralMatrix(); // delete store if set void tDelete(); // delete if tag permits bool reuse(); // true if tag allows reuse void Protect() { tag=-1; } // cannot delete or reuse int Tag() const { return tag; } bool IsZero() const; // test matrix has all zeros void Release() { tag=1; } // del store after next use void Release(int t) { tag=t; } // del store after t accesses void ReleaseAndDelete() { tag=0; } // delete matrix after use void operator<<(const Real*); // assignment from an array void operator<<(const BaseMatrix& X) { Eq(X,this->Type(),true); } // = without checking type void Inject(const GeneralMatrix&); // copy stored els only void operator+=(const BaseMatrix&); void operator-=(const BaseMatrix&); void operator*=(const BaseMatrix&); void operator|=(const BaseMatrix&); void operator&=(const BaseMatrix&); void operator+=(Real); void operator-=(Real r) { operator+=(-r); } void operator*=(Real); void operator/=(Real r) { operator*=(1.0/r); } virtual GeneralMatrix* MakeSolver(); // for solving virtual void Solver(MatrixColX&, const MatrixColX&) {} virtual void GetRow(MatrixRowCol&) = 0; // Get matrix row virtual void RestoreRow(MatrixRowCol&) {} // Restore matrix row virtual void NextRow(MatrixRowCol&); // Go to next row virtual void GetCol(MatrixRowCol&) = 0; // Get matrix col virtual void GetCol(MatrixColX&) = 0; // Get matrix col virtual void RestoreCol(MatrixRowCol&) {} // Restore matrix col virtual void RestoreCol(MatrixColX&) {} // Restore matrix col virtual void NextCol(MatrixRowCol&); // Go to next col virtual void NextCol(MatrixColX&); // Go to next col Real SumSquare() const; Real SumAbsoluteValue() const; Real Sum() const; Real MaximumAbsoluteValue1(int& i) const; Real MinimumAbsoluteValue1(int& i) const; Real Maximum1(int& i) const; Real Minimum1(int& i) const; Real MaximumAbsoluteValue() const; Real MaximumAbsoluteValue2(int& i, int& j) const; Real MinimumAbsoluteValue() const; Real MinimumAbsoluteValue2(int& i, int& j) const; Real Maximum() const; Real Maximum2(int& i, int& j) const; Real Minimum() const; Real Minimum2(int& i, int& j) const; LogAndSign LogDeterminant() const; virtual bool IsEqual(const GeneralMatrix&) const; // same type, same values void CheckStore() const; // check store is non-zero virtual void SetParameters(const GeneralMatrix*) {} // set parameters in GetMatrix operator ReturnMatrix() const; // for building a ReturnMatrix ReturnMatrix ForReturn() const; virtual bool SameStorageType(const GeneralMatrix& A) const; virtual void ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B); virtual void ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B); virtual void ReSize(const GeneralMatrix& A); MatrixInput operator<<(Real); // for loading a list MatrixInput operator<<(int f); // ReturnMatrix Reverse() const; // reverse order of elements void CleanUp(); // to clear store friend class Matrix; friend class nricMatrix; friend class SymmetricMatrix; friend class UpperTriangularMatrix; friend class LowerTriangularMatrix; friend class DiagonalMatrix; friend class CroutMatrix; friend class RowVector; friend class ColumnVector; friend class BandMatrix; friend class LowerBandMatrix; friend class UpperBandMatrix; friend class SymmetricBandMatrix; friend class BaseMatrix; friend class AddedMatrix; friend class MultipliedMatrix; friend class SubtractedMatrix; friend class SPMatrix; friend class KPMatrix; friend class ConcatenatedMatrix; friend class StackedMatrix; friend class SolvedMatrix; friend class ShiftedMatrix; friend class NegShiftedMatrix; friend class ScaledMatrix; friend class TransposedMatrix; friend class ReversedMatrix; friend class NegatedMatrix; friend class InvertedMatrix; friend class RowedMatrix; friend class ColedMatrix; friend class DiagedMatrix; friend class MatedMatrix; friend class GetSubMatrix; friend class ReturnMatrixX; friend class LinearEquationSolver; friend class GenericMatrix; NEW_DELETE(GeneralMatrix) }; class Matrix : public GeneralMatrix // usual rectangular matrix { GeneralMatrix* Image() const; // copy of matrix public: Matrix() {} ~Matrix() {} Matrix(int, int); // standard declaration Matrix(const BaseMatrix&); // evaluate BaseMatrix void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const Matrix& m) { operator=((const BaseMatrix&)m); } MatrixType Type() const; Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+m*ncols; } const Real* operator[](int m) const { return store+m*ncols; } #endif Matrix(const Matrix& gm) { GetMatrix(&gm); } GeneralMatrix* MakeSolver(); Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&); void RestoreCol(MatrixColX&); void NextRow(MatrixRowCol&); void NextCol(MatrixRowCol&); void NextCol(MatrixColX&); virtual void ReSize(int,int); // change dimensions // virtual so we will catch it being used in a vector called as a matrix void ReSize(const GeneralMatrix& A); Real MaximumAbsoluteValue2(int& i, int& j) const; Real MinimumAbsoluteValue2(int& i, int& j) const; Real Maximum2(int& i, int& j) const; Real Minimum2(int& i, int& j) const; friend Real DotProduct(const Matrix& A, const Matrix& B); NEW_DELETE(Matrix) }; class nricMatrix : public Matrix // for use with Numerical // Recipes in C { GeneralMatrix* Image() const; // copy of matrix Real** row_pointer; // points to rows void MakeRowPointer(); // build rowpointer void DeleteRowPointer(); public: nricMatrix() {} nricMatrix(int m, int n) // standard declaration : Matrix(m,n) { MakeRowPointer(); } nricMatrix(const BaseMatrix& bm) // evaluate BaseMatrix : Matrix(bm) { MakeRowPointer(); } void operator=(const BaseMatrix& bm) { DeleteRowPointer(); Matrix::operator=(bm); MakeRowPointer(); } void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const nricMatrix& m) { operator=((const BaseMatrix&)m); } void operator<<(const BaseMatrix& X) { DeleteRowPointer(); Eq(X,this->Type(),true); MakeRowPointer(); } nricMatrix(const nricMatrix& gm) { GetMatrix(&gm); MakeRowPointer(); } void ReSize(int m, int n) // change dimensions { DeleteRowPointer(); Matrix::ReSize(m,n); MakeRowPointer(); } void ReSize(const GeneralMatrix& A); ~nricMatrix() { DeleteRowPointer(); } Real** nric() const { CheckStore(); return row_pointer-1; } void CleanUp(); // to clear store NEW_DELETE(nricMatrix) }; class SymmetricMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: SymmetricMatrix() {} ~SymmetricMatrix() {} SymmetricMatrix(ArrayLengthSpecifier); SymmetricMatrix(const BaseMatrix&); void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const SymmetricMatrix& m) { operator=((const BaseMatrix&)m); } Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+(m*(m+1))/2; } const Real* operator[](int m) const { return store+(m*(m+1))/2; } #endif MatrixType Type() const; SymmetricMatrix(const SymmetricMatrix& gm) { GetMatrix(&gm); } Real SumSquare() const; Real SumAbsoluteValue() const; Real Sum() const; Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&) {} void RestoreCol(MatrixColX&); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int); // change dimensions void ReSize(const GeneralMatrix& A); NEW_DELETE(SymmetricMatrix) }; class UpperTriangularMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: UpperTriangularMatrix() {} ~UpperTriangularMatrix() {} UpperTriangularMatrix(ArrayLengthSpecifier); void operator=(const BaseMatrix&); void operator=(const UpperTriangularMatrix& m) { operator=((const BaseMatrix&)m); } UpperTriangularMatrix(const BaseMatrix&); UpperTriangularMatrix(const UpperTriangularMatrix& gm) { GetMatrix(&gm); } void operator=(Real f) { GeneralMatrix::operator=(f); } Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+m*ncols-(m*(m+1))/2; } const Real* operator[](int m) const { return store+m*ncols-(m*(m+1))/2; } #endif MatrixType Type() const; GeneralMatrix* MakeSolver() { return this; } // for solving void Solver(MatrixColX&, const MatrixColX&); LogAndSign LogDeterminant() const; Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&); void RestoreCol(MatrixColX& c) { RestoreCol((MatrixRowCol&)c); } void NextRow(MatrixRowCol&); void ReSize(int); // change dimensions void ReSize(const GeneralMatrix& A); MatrixBandWidth BandWidth() const; NEW_DELETE(UpperTriangularMatrix) }; class LowerTriangularMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: LowerTriangularMatrix() {} ~LowerTriangularMatrix() {} LowerTriangularMatrix(ArrayLengthSpecifier); LowerTriangularMatrix(const LowerTriangularMatrix& gm) { GetMatrix(&gm); } LowerTriangularMatrix(const BaseMatrix& M); void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const LowerTriangularMatrix& m) { operator=((const BaseMatrix&)m); } Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+(m*(m+1))/2; } const Real* operator[](int m) const { return store+(m*(m+1))/2; } #endif MatrixType Type() const; GeneralMatrix* MakeSolver() { return this; } // for solving void Solver(MatrixColX&, const MatrixColX&); LogAndSign LogDeterminant() const; Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&); void RestoreCol(MatrixColX& c) { RestoreCol((MatrixRowCol&)c); } void NextRow(MatrixRowCol&); void ReSize(int); // change dimensions void ReSize(const GeneralMatrix& A); MatrixBandWidth BandWidth() const; NEW_DELETE(LowerTriangularMatrix) }; class DiagonalMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: DiagonalMatrix() {} ~DiagonalMatrix() {} DiagonalMatrix(ArrayLengthSpecifier); DiagonalMatrix(const BaseMatrix&); DiagonalMatrix(const DiagonalMatrix& gm) { GetMatrix(&gm); } void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const DiagonalMatrix& m) { operator=((const BaseMatrix&)m); } Real& operator()(int, int); // access element Real& operator()(int); // access element Real operator()(int, int) const; // access element Real operator()(int) const; Real& element(int, int); // access element Real& element(int); // access element Real element(int, int) const; // access element Real element(int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real& operator[](int m) { return store[m]; } const Real& operator[](int m) const { return store[m]; } #endif MatrixType Type() const; LogAndSign LogDeterminant() const; Real Trace() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void NextRow(MatrixRowCol&); void NextCol(MatrixRowCol&); void NextCol(MatrixColX&); GeneralMatrix* MakeSolver() { return this; } // for solving void Solver(MatrixColX&, const MatrixColX&); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int); // change dimensions void ReSize(const GeneralMatrix& A); Real* nric() const { CheckStore(); return store-1; } // for use by NRIC MatrixBandWidth BandWidth() const; // ReturnMatrix Reverse() const; // reverse order of elements NEW_DELETE(DiagonalMatrix) }; class RowVector : public Matrix { GeneralMatrix* Image() const; // copy of matrix public: RowVector() { nrows = 1; } ~RowVector() {} RowVector(ArrayLengthSpecifier n) : Matrix(1,n.Value()) {} RowVector(const BaseMatrix&); RowVector(const RowVector& gm) { GetMatrix(&gm); } void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const RowVector& m) { operator=((const BaseMatrix&)m); } Real& operator()(int); // access element Real& element(int); // access element Real operator()(int) const; // access element Real element(int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real& operator[](int m) { return store[m]; } const Real& operator[](int m) const { return store[m]; } #endif MatrixType Type() const; void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void NextCol(MatrixRowCol&); void NextCol(MatrixColX&); void RestoreCol(MatrixRowCol&) {} void RestoreCol(MatrixColX& c); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int); // change dimensions void ReSize(int,int); // in case access is matrix void ReSize(const GeneralMatrix& A); Real* nric() const { CheckStore(); return store-1; } // for use by NRIC void CleanUp(); // to clear store // friend ReturnMatrix GetMatrixRow(Matrix& A, int row); NEW_DELETE(RowVector) }; class ColumnVector : public Matrix { GeneralMatrix* Image() const; // copy of matrix public: ColumnVector() { ncols = 1; } ~ColumnVector() {} ColumnVector(ArrayLengthSpecifier n) : Matrix(n.Value(),1) {} ColumnVector(const BaseMatrix&); ColumnVector(const ColumnVector& gm) { GetMatrix(&gm); } void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const ColumnVector& m) { operator=((const BaseMatrix&)m); } Real& operator()(int); // access element Real& element(int); // access element Real operator()(int) const; // access element Real element(int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real& operator[](int m) { return store[m]; } const Real& operator[](int m) const { return store[m]; } #endif MatrixType Type() const; GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int); // change dimensions void ReSize(int,int); // in case access is matrix void ReSize(const GeneralMatrix& A); Real* nric() const { CheckStore(); return store-1; } // for use by NRIC void CleanUp(); // to clear store // ReturnMatrix Reverse() const; // reverse order of elements NEW_DELETE(ColumnVector) }; class CroutMatrix : public GeneralMatrix // for LU decomposition { int* indx; bool d; bool sing; void ludcmp(); public: CroutMatrix(const BaseMatrix&); MatrixType Type() const; void lubksb(Real*, int=0); ~CroutMatrix(); GeneralMatrix* MakeSolver() { return this; } // for solving LogAndSign LogDeterminant() const; void Solver(MatrixColX&, const MatrixColX&); void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX& c) { GetCol((MatrixRowCol&)c); } void operator=(const BaseMatrix&); void operator=(const CroutMatrix& m) { operator=((const BaseMatrix&)m); } void CleanUp(); // to clear store bool IsEqual(const GeneralMatrix&) const; bool IsSingular() const { return sing; } NEW_DELETE(CroutMatrix) }; // ***************************** band matrices ***************************/ class BandMatrix : public GeneralMatrix // band matrix { GeneralMatrix* Image() const; // copy of matrix protected: void CornerClear() const; // set unused elements to zero short SimpleAddOK(const GeneralMatrix* gm); public: int lower, upper; // band widths BandMatrix() { lower=0; upper=0; CornerClear(); } ~BandMatrix() {} BandMatrix(int n,int lb,int ub) { ReSize(n,lb,ub); CornerClear(); } // standard declaration BandMatrix(const BaseMatrix&); // evaluate BaseMatrix void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const BandMatrix& m) { operator=((const BaseMatrix&)m); } MatrixType Type() const; Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+(upper+lower)*m+lower; } const Real* operator[](int m) const { return store+(upper+lower)*m+lower; } #endif BandMatrix(const BandMatrix& gm) { GetMatrix(&gm); } LogAndSign LogDeterminant() const; GeneralMatrix* MakeSolver(); Real Trace() const; Real SumSquare() const { CornerClear(); return GeneralMatrix::SumSquare(); } Real SumAbsoluteValue() const { CornerClear(); return GeneralMatrix::SumAbsoluteValue(); } Real Sum() const { CornerClear(); return GeneralMatrix::Sum(); } Real MaximumAbsoluteValue() const { CornerClear(); return GeneralMatrix::MaximumAbsoluteValue(); } Real MinimumAbsoluteValue() const { int i, j; return GeneralMatrix::MinimumAbsoluteValue2(i, j); } Real Maximum() const { int i, j; return GeneralMatrix::Maximum2(i, j); } Real Minimum() const { int i, j; return GeneralMatrix::Minimum2(i, j); } void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&); void RestoreCol(MatrixColX& c) { RestoreCol((MatrixRowCol&)c); } void NextRow(MatrixRowCol&); virtual void ReSize(int, int, int); // change dimensions void ReSize(const GeneralMatrix& A); bool SameStorageType(const GeneralMatrix& A) const; void ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B); void ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B); MatrixBandWidth BandWidth() const; void SetParameters(const GeneralMatrix*); MatrixInput operator<<(Real); // will give error MatrixInput operator<<(int f); void operator<<(const Real* r); // will give error // the next is included because Zortech and Borland // cannot find the copy in GeneralMatrix void operator<<(const BaseMatrix& X) { GeneralMatrix::operator<<(X); } NEW_DELETE(BandMatrix) }; class UpperBandMatrix : public BandMatrix // upper band matrix { GeneralMatrix* Image() const; // copy of matrix public: UpperBandMatrix() {} ~UpperBandMatrix() {} UpperBandMatrix(int n, int ubw) // standard declaration : BandMatrix(n, 0, ubw) {} UpperBandMatrix(const BaseMatrix&); // evaluate BaseMatrix void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const UpperBandMatrix& m) { operator=((const BaseMatrix&)m); } MatrixType Type() const; UpperBandMatrix(const UpperBandMatrix& gm) { GetMatrix(&gm); } GeneralMatrix* MakeSolver() { return this; } void Solver(MatrixColX&, const MatrixColX&); LogAndSign LogDeterminant() const; void ReSize(int, int, int); // change dimensions void ReSize(int n,int ubw) // change dimensions { BandMatrix::ReSize(n,0,ubw); } void ReSize(const GeneralMatrix& A) { BandMatrix::ReSize(A); } Real& operator()(int, int); Real operator()(int, int) const; Real& element(int, int); Real element(int, int) const; #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+upper*m; } const Real* operator[](int m) const { return store+upper*m; } #endif NEW_DELETE(UpperBandMatrix) }; class LowerBandMatrix : public BandMatrix // upper band matrix { GeneralMatrix* Image() const; // copy of matrix public: LowerBandMatrix() {} ~LowerBandMatrix() {} LowerBandMatrix(int n, int lbw) // standard declaration : BandMatrix(n, lbw, 0) {} LowerBandMatrix(const BaseMatrix&); // evaluate BaseMatrix void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const LowerBandMatrix& m) { operator=((const BaseMatrix&)m); } MatrixType Type() const; LowerBandMatrix(const LowerBandMatrix& gm) { GetMatrix(&gm); } GeneralMatrix* MakeSolver() { return this; } void Solver(MatrixColX&, const MatrixColX&); LogAndSign LogDeterminant() const; void ReSize(int, int, int); // change dimensions void ReSize(int n,int lbw) // change dimensions { BandMatrix::ReSize(n,lbw,0); } void ReSize(const GeneralMatrix& A) { BandMatrix::ReSize(A); } Real& operator()(int, int); Real operator()(int, int) const; Real& element(int, int); Real element(int, int) const; #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+lower*(m+1); } const Real* operator[](int m) const { return store+lower*(m+1); } #endif NEW_DELETE(LowerBandMatrix) }; class SymmetricBandMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix void CornerClear() const; // set unused elements to zero short SimpleAddOK(const GeneralMatrix* gm); public: int lower; // lower band width SymmetricBandMatrix() { lower=0; CornerClear(); } ~SymmetricBandMatrix() {} SymmetricBandMatrix(int n, int lb) { ReSize(n,lb); CornerClear(); } SymmetricBandMatrix(const BaseMatrix&); void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } void operator=(const SymmetricBandMatrix& m) { operator=((const BaseMatrix&)m); } Real& operator()(int, int); // access element Real& element(int, int); // access element Real operator()(int, int) const; // access element Real element(int, int) const; // access element #ifdef SETUP_C_SUBSCRIPTS Real* operator[](int m) { return store+lower*(m+1); } const Real* operator[](int m) const { return store+lower*(m+1); } #endif MatrixType Type() const; SymmetricBandMatrix(const SymmetricBandMatrix& gm) { GetMatrix(&gm); } GeneralMatrix* MakeSolver(); Real SumSquare() const; Real SumAbsoluteValue() const; Real Sum() const; Real MaximumAbsoluteValue() const { CornerClear(); return GeneralMatrix::MaximumAbsoluteValue(); } Real MinimumAbsoluteValue() const { int i, j; return GeneralMatrix::MinimumAbsoluteValue2(i, j); } Real Maximum() const { int i, j; return GeneralMatrix::Maximum2(i, j); } Real Minimum() const { int i, j; return GeneralMatrix::Minimum2(i, j); } Real Trace() const; LogAndSign LogDeterminant() const; void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void RestoreCol(MatrixRowCol&) {} void RestoreCol(MatrixColX&); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int,int); // change dimensions void ReSize(const GeneralMatrix& A); bool SameStorageType(const GeneralMatrix& A) const; void ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix& B); void ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix& B); MatrixBandWidth BandWidth() const; void SetParameters(const GeneralMatrix*); NEW_DELETE(SymmetricBandMatrix) }; class BandLUMatrix : public GeneralMatrix // for LU decomposition of band matrix { int* indx; bool d; bool sing; // true if singular Real* store2; int storage2; void ludcmp(); int m1,m2; // lower and upper public: BandLUMatrix(const BaseMatrix&); MatrixType Type() const; void lubksb(Real*, int=0); ~BandLUMatrix(); GeneralMatrix* MakeSolver() { return this; } // for solving LogAndSign LogDeterminant() const; void Solver(MatrixColX&, const MatrixColX&); void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX& c) { GetCol((MatrixRowCol&)c); } void operator=(const BaseMatrix&); void operator=(const BandLUMatrix& m) { operator=((const BaseMatrix&)m); } void CleanUp(); // to clear store bool IsEqual(const GeneralMatrix&) const; bool IsSingular() const { return sing; } NEW_DELETE(BandLUMatrix) }; // ************************** special matrices **************************** class IdentityMatrix : public GeneralMatrix { GeneralMatrix* Image() const; // copy of matrix public: IdentityMatrix() {} ~IdentityMatrix() {} IdentityMatrix(ArrayLengthSpecifier n) : GeneralMatrix(1) { nrows = ncols = n.Value(); *store = 1; } IdentityMatrix(const IdentityMatrix& gm) { GetMatrix(&gm); } IdentityMatrix(const BaseMatrix&); void operator=(const BaseMatrix&); void operator=(Real f) { GeneralMatrix::operator=(f); } MatrixType Type() const; LogAndSign LogDeterminant() const; Real Trace() const; Real SumSquare() const; Real SumAbsoluteValue() const; Real Sum() const { return Trace(); } void GetRow(MatrixRowCol&); void GetCol(MatrixRowCol&); void GetCol(MatrixColX&); void NextRow(MatrixRowCol&); void NextCol(MatrixRowCol&); void NextCol(MatrixColX&); GeneralMatrix* MakeSolver() { return this; } // for solving void Solver(MatrixColX&, const MatrixColX&); GeneralMatrix* Transpose(TransposedMatrix*, MatrixType); void ReSize(int n); void ReSize(const GeneralMatrix& A); MatrixBandWidth BandWidth() const; // ReturnMatrix Reverse() const; // reverse order of elements NEW_DELETE(IdentityMatrix) }; // ************************** GenericMatrix class ************************/ class GenericMatrix : public BaseMatrix { GeneralMatrix* gm; int search(const BaseMatrix* bm) const; friend class BaseMatrix; public: GenericMatrix() : gm(0) {} GenericMatrix(const BaseMatrix& bm) { gm = ((BaseMatrix&)bm).Evaluate(); gm = gm->Image(); } GenericMatrix(const GenericMatrix& bm) { gm = bm.gm->Image(); } void operator=(const GenericMatrix&); void operator=(const BaseMatrix&); void operator+=(const BaseMatrix&); void operator-=(const BaseMatrix&); void operator*=(const BaseMatrix&); void operator|=(const BaseMatrix&); void operator&=(const BaseMatrix&); void operator+=(Real); void operator-=(Real r) { operator+=(-r); } void operator*=(Real); void operator/=(Real r) { operator*=(1.0/r); } ~GenericMatrix() { delete gm; } void CleanUp() { delete gm; gm = 0; } void Release() { gm->Release(); } GeneralMatrix* Evaluate(MatrixType = MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(GenericMatrix) }; // *************************** temporary classes *************************/ class MultipliedMatrix : public BaseMatrix { protected: // if these union statements cause problems, simply remove them // and declare the items individually union { const BaseMatrix* bm1; GeneralMatrix* gm1; }; // pointers to summands union { const BaseMatrix* bm2; GeneralMatrix* gm2; }; MultipliedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : bm1(bm1x),bm2(bm2x) {} int search(const BaseMatrix*) const; friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~MultipliedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(MultipliedMatrix) }; class AddedMatrix : public MultipliedMatrix { protected: AddedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : MultipliedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~AddedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(AddedMatrix) }; class SPMatrix : public AddedMatrix { protected: SPMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : AddedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~SPMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; #ifndef TEMPS_DESTROYED_QUICKLY friend SPMatrix SP(const BaseMatrix&, const BaseMatrix&); #else friend SPMatrix& SP(const BaseMatrix&, const BaseMatrix&); #endif NEW_DELETE(SPMatrix) }; class KPMatrix : public MultipliedMatrix { protected: KPMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : MultipliedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~KPMatrix() {} MatrixBandWidth BandWidth() const; GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); #ifndef TEMPS_DESTROYED_QUICKLY friend KPMatrix KP(const BaseMatrix&, const BaseMatrix&); #else friend KPMatrix& KP(const BaseMatrix&, const BaseMatrix&); #endif NEW_DELETE(KPMatrix) }; class ConcatenatedMatrix : public MultipliedMatrix { protected: ConcatenatedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : MultipliedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~ConcatenatedMatrix() {} MatrixBandWidth BandWidth() const; GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); NEW_DELETE(ConcatenatedMatrix) }; class StackedMatrix : public ConcatenatedMatrix { protected: StackedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : ConcatenatedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~StackedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); NEW_DELETE(StackedMatrix) }; class SolvedMatrix : public MultipliedMatrix { SolvedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : MultipliedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class InvertedMatrix; // for operator* public: ~SolvedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(SolvedMatrix) }; class SubtractedMatrix : public AddedMatrix { SubtractedMatrix(const BaseMatrix* bm1x, const BaseMatrix* bm2x) : AddedMatrix(bm1x,bm2x) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~SubtractedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); NEW_DELETE(SubtractedMatrix) }; class ShiftedMatrix : public BaseMatrix { protected: union { const BaseMatrix* bm; GeneralMatrix* gm; }; Real f; ShiftedMatrix(const BaseMatrix* bmx, Real fx) : bm(bmx),f(fx) {} int search(const BaseMatrix*) const; friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~ShiftedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); #ifndef TEMPS_DESTROYED_QUICKLY friend ShiftedMatrix operator+(Real f, const BaseMatrix& BM); // { return ShiftedMatrix(&BM, f); } #endif NEW_DELETE(ShiftedMatrix) }; class NegShiftedMatrix : public ShiftedMatrix { protected: NegShiftedMatrix(Real fx, const BaseMatrix* bmx) : ShiftedMatrix(bmx,fx) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~NegShiftedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); #ifndef TEMPS_DESTROYED_QUICKLY friend NegShiftedMatrix operator-(Real, const BaseMatrix&); #else friend NegShiftedMatrix& operator-(Real, const BaseMatrix&); #endif NEW_DELETE(NegShiftedMatrix) }; class ScaledMatrix : public ShiftedMatrix { ScaledMatrix(const BaseMatrix* bmx, Real fx) : ShiftedMatrix(bmx,fx) {} friend class BaseMatrix; friend class GeneralMatrix; friend class GenericMatrix; public: ~ScaledMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; #ifndef TEMPS_DESTROYED_QUICKLY friend ScaledMatrix operator*(Real f, const BaseMatrix& BM); //{ return ScaledMatrix(&BM, f); } #endif NEW_DELETE(ScaledMatrix) }; class NegatedMatrix : public BaseMatrix { protected: union { const BaseMatrix* bm; GeneralMatrix* gm; }; NegatedMatrix(const BaseMatrix* bmx) : bm(bmx) {} int search(const BaseMatrix*) const; private: friend class BaseMatrix; public: ~NegatedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(NegatedMatrix) }; class TransposedMatrix : public NegatedMatrix { TransposedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~TransposedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(TransposedMatrix) }; class ReversedMatrix : public NegatedMatrix { ReversedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~ReversedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); NEW_DELETE(ReversedMatrix) }; class InvertedMatrix : public NegatedMatrix { InvertedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} public: ~InvertedMatrix() {} #ifndef TEMPS_DESTROYED_QUICKLY SolvedMatrix operator*(const BaseMatrix&) const; // inverse(A) * B ScaledMatrix operator*(Real t) const { return BaseMatrix::operator*(t); } #else SolvedMatrix& operator*(const BaseMatrix&); // inverse(A) * B ScaledMatrix& operator*(Real t) const { return BaseMatrix::operator*(t); } #endif friend class BaseMatrix; GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(InvertedMatrix) }; class RowedMatrix : public NegatedMatrix { RowedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~RowedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(RowedMatrix) }; class ColedMatrix : public NegatedMatrix { ColedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~ColedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(ColedMatrix) }; class DiagedMatrix : public NegatedMatrix { DiagedMatrix(const BaseMatrix* bmx) : NegatedMatrix(bmx) {} friend class BaseMatrix; public: ~DiagedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(DiagedMatrix) }; class MatedMatrix : public NegatedMatrix { int nr, nc; MatedMatrix(const BaseMatrix* bmx, int nrx, int ncx) : NegatedMatrix(bmx), nr(nrx), nc(ncx) {} friend class BaseMatrix; public: ~MatedMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); MatrixBandWidth BandWidth() const; NEW_DELETE(MatedMatrix) }; class ReturnMatrixX : public BaseMatrix // for matrix return { GeneralMatrix* gm; int search(const BaseMatrix*) const; public: ~ReturnMatrixX() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); friend class BaseMatrix; #ifdef TEMPS_DESTROYED_QUICKLY_R ReturnMatrixX(const ReturnMatrixX& tm); #else ReturnMatrixX(const ReturnMatrixX& tm) : gm(tm.gm) {} #endif ReturnMatrixX(const GeneralMatrix* gmx) : gm((GeneralMatrix*&)gmx) {} // ReturnMatrixX(GeneralMatrix&); MatrixBandWidth BandWidth() const; NEW_DELETE(ReturnMatrixX) }; // ************************** submatrices ******************************/ class GetSubMatrix : public NegatedMatrix { int row_skip; int row_number; int col_skip; int col_number; bool IsSym; GetSubMatrix (const BaseMatrix* bmx, int rs, int rn, int cs, int cn, bool is) : NegatedMatrix(bmx), row_skip(rs), row_number(rn), col_skip(cs), col_number(cn), IsSym(is) {} void SetUpLHS(); friend class BaseMatrix; public: GetSubMatrix(const GetSubMatrix& g) : NegatedMatrix(g.bm), row_skip(g.row_skip), row_number(g.row_number), col_skip(g.col_skip), col_number(g.col_number), IsSym(g.IsSym) {} ~GetSubMatrix() {} GeneralMatrix* Evaluate(MatrixType mt=MatrixTypeUnSp); void operator=(const BaseMatrix&); void operator+=(const BaseMatrix&); void operator-=(const BaseMatrix&); void operator=(const GetSubMatrix& m) { operator=((const BaseMatrix&)m); } void operator<<(const BaseMatrix&); void operator<<(const Real*); // copy from array MatrixInput operator<<(Real); // for loading a list MatrixInput operator<<(int f); void operator=(Real); // copy from constant void operator+=(Real); // add constant void operator-=(Real r) { operator+=(-r); } // subtract constant void operator*=(Real); // multiply by constant void operator/=(Real r) { operator*=(1.0/r); } // divide by constant void Inject(const GeneralMatrix&); // copy stored els only MatrixBandWidth BandWidth() const; NEW_DELETE(GetSubMatrix) }; // ******************** linear equation solving ****************************/ class LinearEquationSolver : public BaseMatrix { GeneralMatrix* gm; int search(const BaseMatrix*) const { return 0; } friend class BaseMatrix; public: LinearEquationSolver(const BaseMatrix& bm); ~LinearEquationSolver() { delete gm; } void CleanUp() { delete gm; } GeneralMatrix* Evaluate(MatrixType) { return gm; } // probably should have an error message if MatrixType != UnSp NEW_DELETE(LinearEquationSolver) }; // ************************** matrix input *******************************/ class MatrixInput // for reading a list of values into a matrix // the difficult part is detecting a mismatch // in the number of elements { int n; // number values still to be read Real* r; // pointer to next location to be read to public: MatrixInput(const MatrixInput& mi) : n(mi.n), r(mi.r) {} MatrixInput(int nx, Real* rx) : n(nx), r(rx) {} ~MatrixInput(); MatrixInput operator<<(Real); MatrixInput operator<<(int f); friend class GeneralMatrix; }; // **************** a very simple integer array class ********************/ // A minimal array class to imitate a C style array but giving dynamic storage // mostly intended for internal use by newmat class SimpleIntArray : public Janitor { protected: int* a; // pointer to the array int n; // length of the array public: SimpleIntArray(int xn); // build an array length xn ~SimpleIntArray(); // return the space to memory int& operator[](int i); // access element of the array - start at 0 int operator[](int i) const; // access element of constant array void operator=(int ai); // set the array equal to a constant void operator=(const SimpleIntArray& b); // copy the elements of an array SimpleIntArray(const SimpleIntArray& b); // make a new array equal to an existing one int Size() const { return n; } // return the size of the array int* Data() { return a; } // pointer to the data const int* Data() const { return a; } // pointer to the data void ReSize(int i, bool keep = false); // change length, keep data if keep = true void CleanUp() { ReSize(0); } NEW_DELETE(SimpleIntArray) }; // *************************** exceptions ********************************/ class NPDException : public Runtime_error // Not positive definite { public: static unsigned long Select; // for identifying exception NPDException(const GeneralMatrix&); }; class ConvergenceException : public Runtime_error { public: static unsigned long Select; // for identifying exception ConvergenceException(const GeneralMatrix& A); ConvergenceException(const char* c); }; class SingularException : public Runtime_error { public: static unsigned long Select; // for identifying exception SingularException(const GeneralMatrix& A); }; class OverflowException : public Runtime_error { public: static unsigned long Select; // for identifying exception OverflowException(const char* c); }; class ProgramException : public Logic_error { protected: ProgramException(); public: static unsigned long Select; // for identifying exception ProgramException(const char* c); ProgramException(const char* c, const GeneralMatrix&); ProgramException(const char* c, const GeneralMatrix&, const GeneralMatrix&); ProgramException(const char* c, MatrixType, MatrixType); }; class IndexException : public Logic_error { public: static unsigned long Select; // for identifying exception IndexException(int i, const GeneralMatrix& A); IndexException(int i, int j, const GeneralMatrix& A); // next two are for access via element function IndexException(int i, const GeneralMatrix& A, bool); IndexException(int i, int j, const GeneralMatrix& A, bool); }; class VectorException : public Logic_error // cannot convert to vector { public: static unsigned long Select; // for identifying exception VectorException(); VectorException(const GeneralMatrix& A); }; class NotSquareException : public Logic_error { public: static unsigned long Select; // for identifying exception NotSquareException(const GeneralMatrix& A); }; class SubMatrixDimensionException : public Logic_error { public: static unsigned long Select; // for identifying exception SubMatrixDimensionException(); }; class IncompatibleDimensionsException : public Logic_error { public: static unsigned long Select; // for identifying exception IncompatibleDimensionsException(); IncompatibleDimensionsException(const GeneralMatrix&, const GeneralMatrix&); }; class NotDefinedException : public Logic_error { public: static unsigned long Select; // for identifying exception NotDefinedException(const char* op, const char* matrix); }; class CannotBuildException : public Logic_error { public: static unsigned long Select; // for identifying exception CannotBuildException(const char* matrix); }; class InternalException : public Logic_error { public: static unsigned long Select; // for identifying exception InternalException(const char* c); }; // ************************ functions ************************************ // bool operator==(const GeneralMatrix& A, const GeneralMatrix& B); bool operator==(const BaseMatrix& A, const BaseMatrix& B); inline bool operator!=(const GeneralMatrix& A, const GeneralMatrix& B) { return ! (A==B); } inline bool operator!=(const BaseMatrix& A, const BaseMatrix& B) { return ! (A==B); } // inequality operators are dummies included for compatibility // with STL. They throw an exception if actually called. inline bool operator<=(const BaseMatrix& A, const BaseMatrix&) { A.IEQND(); return true; } inline bool operator>=(const BaseMatrix& A, const BaseMatrix&) { A.IEQND(); return true; } inline bool operator<(const BaseMatrix& A, const BaseMatrix&) { A.IEQND(); return true; } inline bool operator>(const BaseMatrix& A, const BaseMatrix&) { A.IEQND(); return true; } bool IsZero(const BaseMatrix& A); // *********************** friend functions ****************************** // bool Rectangular(MatrixType a, MatrixType b, MatrixType c); bool Compare(const MatrixType&, MatrixType&); Real DotProduct(const Matrix& A, const Matrix& B); #ifndef TEMPS_DESTROYED_QUICKLY SPMatrix SP(const BaseMatrix&, const BaseMatrix&); KPMatrix KP(const BaseMatrix&, const BaseMatrix&); ShiftedMatrix operator+(Real f, const BaseMatrix& BM); NegShiftedMatrix operator-(Real, const BaseMatrix&); ScaledMatrix operator*(Real f, const BaseMatrix& BM); #else SPMatrix& SP(const BaseMatrix&, const BaseMatrix&); KPMatrix& KP(const BaseMatrix&, const BaseMatrix&); NegShiftedMatrix& operator-(Real, const BaseMatrix&); #endif // ********************* inline functions ******************************** // inline LogAndSign LogDeterminant(const BaseMatrix& B) { return B.LogDeterminant(); } inline Real Determinant(const BaseMatrix& B) { return B.Determinant(); } inline Real SumSquare(const BaseMatrix& B) { return B.SumSquare(); } inline Real NormFrobenius(const BaseMatrix& B) { return B.NormFrobenius(); } inline Real Trace(const BaseMatrix& B) { return B.Trace(); } inline Real SumAbsoluteValue(const BaseMatrix& B) { return B.SumAbsoluteValue(); } inline Real Sum(const BaseMatrix& B) { return B.Sum(); } inline Real MaximumAbsoluteValue(const BaseMatrix& B) { return B.MaximumAbsoluteValue(); } inline Real MinimumAbsoluteValue(const BaseMatrix& B) { return B.MinimumAbsoluteValue(); } inline Real Maximum(const BaseMatrix& B) { return B.Maximum(); } inline Real Minimum(const BaseMatrix& B) { return B.Minimum(); } inline Real Norm1(const BaseMatrix& B) { return B.Norm1(); } inline Real Norm1(RowVector& RV) { return RV.MaximumAbsoluteValue(); } inline Real NormInfinity(const BaseMatrix& B) { return B.NormInfinity(); } inline Real NormInfinity(ColumnVector& CV) { return CV.MaximumAbsoluteValue(); } inline bool IsZero(const GeneralMatrix& A) { return A.IsZero(); } #ifdef TEMPS_DESTROYED_QUICKLY inline ShiftedMatrix& operator+(Real f, const BaseMatrix& BM) { return BM + f; } inline ScaledMatrix& operator*(Real f, const BaseMatrix& BM) { return BM * f; } #endif // these are moved out of the class definitions because of a problem // with the Intel 8.1 compiler #ifndef TEMPS_DESTROYED_QUICKLY inline ShiftedMatrix operator+(Real f, const BaseMatrix& BM) { return ShiftedMatrix(&BM, f); } inline ScaledMatrix operator*(Real f, const BaseMatrix& BM) { return ScaledMatrix(&BM, f); } #endif inline MatrixInput MatrixInput::operator<<(int f) { return *this << (Real)f; } inline MatrixInput GeneralMatrix::operator<<(int f) { return *this << (Real)f; } inline MatrixInput BandMatrix::operator<<(int f) { return *this << (Real)f; } inline MatrixInput GetSubMatrix::operator<<(int f) { return *this << (Real)f; } #ifdef use_namespace } #endif #endif // body file: newmat1.cpp // body file: newmat2.cpp // body file: newmat3.cpp // body file: newmat4.cpp // body file: newmat5.cpp // body file: newmat6.cpp // body file: newmat7.cpp // body file: newmat8.cpp // body file: newmatex.cpp // body file: bandmat.cpp // body file: submat.cpp newmat-1.10.4/newmat.lfl0000644001161000116100000000005407312557614013277 0ustar rzrrzrnewmat.h newmatap.h newmatio.h myexcept.cpp newmat-1.10.4/newmat1.cpp0000644001161000116100000001157507550522764013401 0ustar rzrrzr//$$ newmat1.cpp Matrix type functions // Copyright (C) 1991,2,3,4: R B Davies //#define WANT_STREAM #include "newmat.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,1); ++ExeCount; } #else #define REPORT {} #endif /************************* MatrixType functions *****************************/ // all operations to return MatrixTypes which correspond to valid types // of matrices. // Eg: if it has the Diagonal attribute, then it must also have // Upper, Lower, Band and Symmetric. MatrixType MatrixType::operator*(const MatrixType& mt) const { REPORT int a = attribute & mt.attribute & ~Symmetric; a |= (a & Diagonal) * 31; // recognise diagonal return MatrixType(a); } MatrixType MatrixType::SP(const MatrixType& mt) const // elementwise product // Lower, Upper, Diag, Band if only one is // Symmetric, Ones, Valid (and Real) if both are // Need to include Lower & Upper => Diagonal // Will need to include both Skew => Symmetric { REPORT int a = ((attribute | mt.attribute) & ~(Symmetric + Valid + Ones)) | (attribute & mt.attribute); if ((a & Lower) != 0 && (a & Upper) != 0) a |= Diagonal; a |= (a & Diagonal) * 31; // recognise diagonal return MatrixType(a); } MatrixType MatrixType::KP(const MatrixType& mt) const // Kronecker product // Lower, Upper, Diag, Symmetric, Band, Valid if both are // Do not treat Band separately // Ones is complicated so leave this out { REPORT int a = (attribute & mt.attribute) & ~Ones; return MatrixType(a); } MatrixType MatrixType::i() const // type of inverse { REPORT int a = attribute & ~(Band+LUDeco); a |= (a & Diagonal) * 31; // recognise diagonal return MatrixType(a); } MatrixType MatrixType::t() const // swap lower and upper attributes // assume Upper is in bit above Lower { REPORT int a = attribute; a ^= (((a >> 1) ^ a) & Lower) * 3; return MatrixType(a); } MatrixType MatrixType::MultRHS() const { REPORT // remove symmetric attribute unless diagonal return (attribute >= Dg) ? attribute : (attribute & ~Symmetric); } bool Rectangular(MatrixType a, MatrixType b, MatrixType c) { REPORT return ((a.attribute | b.attribute | c.attribute) & ~MatrixType::Valid) == 0; } const char* MatrixType::Value() const { // make a string with the name of matrix with the given attributes switch (attribute) { case Valid: REPORT return "Rect "; case Valid+Symmetric: REPORT return "Sym "; case Valid+Band: REPORT return "Band "; case Valid+Symmetric+Band: REPORT return "SmBnd"; case Valid+Upper: REPORT return "UT "; case Valid+Diagonal+Symmetric+Band+Upper+Lower: REPORT return "Diag "; case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones: REPORT return "Ident"; case Valid+Band+Upper: REPORT return "UpBnd"; case Valid+Lower: REPORT return "LT "; case Valid+Band+Lower: REPORT return "LwBnd"; default: REPORT if (!(attribute & Valid)) return "UnSp "; if (attribute & LUDeco) return (attribute & Band) ? "BndLU" : "Crout"; return "?????"; } } GeneralMatrix* MatrixType::New(int nr, int nc, BaseMatrix* bm) const { // make a new matrix with the given attributes Tracer tr("New"); GeneralMatrix* gm=0; // initialised to keep gnu happy switch (attribute) { case Valid: REPORT if (nc==1) { gm = new ColumnVector(nr); break; } if (nr==1) { gm = new RowVector(nc); break; } gm = new Matrix(nr, nc); break; case Valid+Symmetric: REPORT gm = new SymmetricMatrix(nr); break; case Valid+Band: { REPORT MatrixBandWidth bw = bm->BandWidth(); gm = new BandMatrix(nr,bw.lower,bw.upper); break; } case Valid+Symmetric+Band: REPORT gm = new SymmetricBandMatrix(nr,bm->BandWidth().lower); break; case Valid+Upper: REPORT gm = new UpperTriangularMatrix(nr); break; case Valid+Diagonal+Symmetric+Band+Upper+Lower: REPORT gm = new DiagonalMatrix(nr); break; case Valid+Band+Upper: REPORT gm = new UpperBandMatrix(nr,bm->BandWidth().upper); break; case Valid+Lower: REPORT gm = new LowerTriangularMatrix(nr); break; case Valid+Band+Lower: REPORT gm = new LowerBandMatrix(nr,bm->BandWidth().lower); break; case Valid+Diagonal+Symmetric+Band+Upper+Lower+Ones: REPORT gm = new IdentityMatrix(nr); break; default: Throw(ProgramException("Invalid matrix type")); } MatrixErrorNoSpace(gm); gm->Protect(); return gm; } #ifdef use_namespace } #endif newmat-1.10.4/newmat2.cpp0000644001161000116100000004452707416410772013401 0ustar rzrrzr//$$ newmat2.cpp Matrix row and column operations // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH #include "include.h" #include "newmat.h" #include "newmatrc.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,2); ++ExeCount; } #else #define REPORT {} #endif //#define MONITOR(what,storage,store) { cout << what << " " << storage << " at " << (long)store << "\n"; } #define MONITOR(what,store,storage) {} /************************** Matrix Row/Col functions ************************/ void MatrixRowCol::Add(const MatrixRowCol& mrc) { // THIS += mrc REPORT int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; if (f < skip) f = skip; if (l > lx) l = lx; l -= f; if (l<=0) return; Real* elx=data+(f-skip); Real* el=mrc.data+(f-mrc.skip); while (l--) *elx++ += *el++; } void MatrixRowCol::AddScaled(const MatrixRowCol& mrc, Real x) { REPORT // THIS += (mrc * x) int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; if (f < skip) f = skip; if (l > lx) l = lx; l -= f; if (l<=0) return; Real* elx=data+(f-skip); Real* el=mrc.data+(f-mrc.skip); while (l--) *elx++ += *el++ * x; } void MatrixRowCol::Sub(const MatrixRowCol& mrc) { REPORT // THIS -= mrc int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; if (f < skip) f = skip; if (l > lx) l = lx; l -= f; if (l<=0) return; Real* elx=data+(f-skip); Real* el=mrc.data+(f-mrc.skip); while (l--) *elx++ -= *el++; } void MatrixRowCol::Inject(const MatrixRowCol& mrc) // copy stored elements only { REPORT int f = mrc.skip; int l = f + mrc.storage; int lx = skip + storage; if (f < skip) f = skip; if (l > lx) l = lx; l -= f; if (l<=0) return; Real* elx=data+(f-skip); Real* ely=mrc.data+(f-mrc.skip); while (l--) *elx++ = *ely++; } Real DotProd(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) { REPORT // not accessed int f = mrc1.skip; int f2 = mrc2.skip; int l = f + mrc1.storage; int l2 = f2 + mrc2.storage; if (f < f2) f = f2; if (l > l2) l = l2; l -= f; if (l<=0) return 0.0; Real* el1=mrc1.data+(f-mrc1.skip); Real* el2=mrc2.data+(f-mrc2.skip); Real sum = 0.0; while (l--) sum += *el1++ * *el2++; return sum; } void MatrixRowCol::Add(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) { // THIS = mrc1 + mrc2 int f = skip; int l = skip + storage; int f1 = mrc1.skip; int l1 = f1 + mrc1.storage; if (f1l) l1=l; int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; if (f2l) l2=l; Real* el = data + (f-skip); Real* el1 = mrc1.data+(f1-mrc1.skip); Real* el2 = mrc2.data+(f2-mrc2.skip); if (f1l) l1=l; int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; if (f2l) l2=l; Real* el = data + (f-skip); Real* el1 = mrc1.data+(f1-mrc1.skip); Real* el2 = mrc2.data+(f2-mrc2.skip); if (f1 lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = x; l1 = l-f; while (l1--) *elx++ = *ely++ + x; lx -= l; while (lx--) *elx++ = x; } void MatrixRowCol::NegAdd(const MatrixRowCol& mrc1, Real x) { // THIS = x - mrc1 REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = x; l1 = l-f; while (l1--) *elx++ = x - *ely++; lx -= l; while (lx--) *elx++ = x; } void MatrixRowCol::RevSub(const MatrixRowCol& mrc1) { // THIS = mrc - THIS REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) { *elx = - *elx; elx++; } l1 = l-f; while (l1--) { *elx = *ely++ - *elx; elx++; } lx -= l; while (lx--) { *elx = - *elx; elx++; } } void MatrixRowCol::ConCat(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) { // THIS = mrc1 | mrc2 REPORT int f1 = mrc1.skip; int l1 = f1 + mrc1.storage; int lx = skip + storage; if (f1 < skip) { f1 = skip; if (l1 < f1) l1 = f1; } if (l1 > lx) { l1 = lx; if (f1 > lx) f1 = lx; } Real* elx = data; int i = f1-skip; while (i--) *elx++ =0.0; i = l1-f1; if (i) // in case f1 would take ely out of range { Real* ely = mrc1.data+(f1-mrc1.skip); while (i--) *elx++ = *ely++; } int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; i = mrc1.length; int skipx = l1 - i; lx -= i; // addresses rel to second seg, maybe -ve if (f2 < skipx) { f2 = skipx; if (l2 < f2) l2 = f2; } if (l2 > lx) { l2 = lx; if (f2 > lx) f2 = lx; } i = f2-skipx; while (i--) *elx++ = 0.0; i = l2-f2; if (i) // in case f2 would take ely out of range { Real* ely = mrc2.data+(f2-mrc2.skip); while (i--) *elx++ = *ely++; } lx -= l2; while (lx--) *elx++ = 0.0; } void MatrixRowCol::Multiply(const MatrixRowCol& mrc1) // element by element multiply into { REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0; l1 = l-f; while (l1--) *elx++ *= *ely++; lx -= l; while (lx--) *elx++ = 0; } void MatrixRowCol::Multiply(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) // element by element multiply { int f = skip; int l = skip + storage; int f1 = mrc1.skip; int l1 = f1 + mrc1.storage; if (f1l) l1=l; int f2 = mrc2.skip; int l2 = f2 + mrc2.storage; if (f2l) l2=l; Real* el = data + (f-skip); int i; if (f1l2) l1 = l2; if (l1<=f1) { REPORT i = l-f; while (i--) *el++ = 0.0; } // disjoint else { REPORT Real* el1 = mrc1.data+(f1-mrc1.skip); Real* el2 = mrc2.data+(f1-mrc2.skip); i = f1-f ; while (i--) *el++ = 0.0; i = l1-f1; while (i--) *el++ = *el1++ * *el2++; i = l-l1; while (i--) *el++ = 0.0; } } void MatrixRowCol::KP(const MatrixRowCol& mrc1, const MatrixRowCol& mrc2) // row for Kronecker product { int f = skip; int s = storage; Real* el = data; int i; i = mrc1.skip * mrc2.length; if (i > f) { i -= f; f = 0; if (i > s) { i = s; s = 0; } else s -= i; while (i--) *el++ = 0.0; if (s == 0) return; } else f -= i; i = mrc1.storage; Real* el1 = mrc1.data; int mrc2_skip = mrc2.skip; int mrc2_storage = mrc2.storage; int mrc2_length = mrc2.length; int mrc2_remain = mrc2_length - mrc2_skip - mrc2_storage; while (i--) { int j; Real* el2 = mrc2.data; Real vel1 = *el1; if (f == 0 && mrc2_length <= s) { j = mrc2_skip; s -= j; while (j--) *el++ = 0.0; j = mrc2_storage; s -= j; while (j--) *el++ = vel1 * *el2++; j = mrc2_remain; s -= j; while (j--) *el++ = 0.0; } else if (f >= mrc2_length) f -= mrc2_length; else { j = mrc2_skip; if (j > f) { j -= f; f = 0; if (j > s) { j = s; s = 0; } else s -= j; while (j--) *el++ = 0.0; } else f -= j; j = mrc2_storage; if (j > f) { j -= f; el2 += f; f = 0; if (j > s) { j = s; s = 0; } else s -= j; while (j--) *el++ = vel1 * *el2++; } else f -= j; j = mrc2_remain; if (j > f) { j -= f; f = 0; if (j > s) { j = s; s = 0; } else s -= j; while (j--) *el++ = 0.0; } else f -= j; } if (s == 0) return; ++el1; } i = (mrc1.length - mrc1.skip - mrc1.storage) * mrc2.length; if (i > f) { i -= f; if (i > s) i = s; while (i--) *el++ = 0.0; } } void MatrixRowCol::Copy(const MatrixRowCol& mrc1) { // THIS = mrc1 REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = 0; if (l-f) ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ = *ely++; lx -= l; while (lx--) *elx++ = 0.0; } void MatrixRowCol::CopyCheck(const MatrixRowCol& mrc1) // Throw an exception if this would lead to a loss of data { REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip || l > lx) Throw(ProgramException("Illegal Conversion")); Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ = *ely++; lx -= l; while (lx--) *elx++ = 0.0; } void MatrixRowCol::Check(const MatrixRowCol& mrc1) // Throw an exception if +=, -=, copy etc would lead to a loss of data { REPORT int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip || l > lx) Throw(ProgramException("Illegal Conversion")); } void MatrixRowCol::Check() // Throw an exception if +=, -= of constant would lead to a loss of data // that is: check full row is present // may not be appropriate for symmetric matrices { REPORT if (skip!=0 || storage!=length) Throw(ProgramException("Illegal Conversion")); } void MatrixRowCol::Negate(const MatrixRowCol& mrc1) { // THIS = -mrc1 REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ = - *ely++; lx -= l; while (lx--) *elx++ = 0.0; } void MatrixRowCol::Multiply(const MatrixRowCol& mrc1, Real s) { // THIS = mrc1 * s REPORT if (!storage) return; int f = mrc1.skip; int l = f + mrc1.storage; int lx = skip + storage; if (f < skip) { f = skip; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = data; Real* ely = mrc1.data+(f-mrc1.skip); int l1 = f-skip; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ = *ely++ * s; lx -= l; while (lx--) *elx++ = 0.0; } void DiagonalMatrix::Solver(MatrixColX& mrc, const MatrixColX& mrc1) { // mrc = mrc / mrc1 (elementwise) REPORT int f = mrc1.skip; int f0 = mrc.skip; int l = f + mrc1.storage; int lx = f0 + mrc.storage; if (f < f0) { f = f0; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = mrc.data; Real* eld = store+f; int l1 = f-f0; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ /= *eld++; lx -= l; while (lx--) *elx++ = 0.0; // Solver makes sure input and output point to same memory } void IdentityMatrix::Solver(MatrixColX& mrc, const MatrixColX& mrc1) { // mrc = mrc / mrc1 (elementwise) REPORT int f = mrc1.skip; int f0 = mrc.skip; int l = f + mrc1.storage; int lx = f0 + mrc.storage; if (f < f0) { f = f0; if (l < f) l = f; } if (l > lx) { l = lx; if (f > lx) f = lx; } Real* elx = mrc.data; Real eldv = *store; int l1 = f-f0; while (l1--) *elx++ = 0.0; l1 = l-f; while (l1--) *elx++ /= eldv; lx -= l; while (lx--) *elx++ = 0.0; // Solver makes sure input and output point to same memory } void MatrixRowCol::Copy(const Real*& r) { // THIS = *r REPORT Real* elx = data; const Real* ely = r+skip; r += length; int l = storage; while (l--) *elx++ = *ely++; } void MatrixRowCol::Copy(Real r) { // THIS = r REPORT Real* elx = data; int l = storage; while (l--) *elx++ = r; } void MatrixRowCol::Zero() { // THIS = 0 REPORT Real* elx = data; int l = storage; while (l--) *elx++ = 0; } void MatrixRowCol::Multiply(Real r) { // THIS *= r REPORT Real* elx = data; int l = storage; while (l--) *elx++ *= r; } void MatrixRowCol::Add(Real r) { // THIS += r REPORT Real* elx = data; int l = storage; while (l--) *elx++ += r; } Real MatrixRowCol::SumAbsoluteValue() { REPORT Real sum = 0.0; Real* elx = data; int l = storage; while (l--) sum += fabs(*elx++); return sum; } // max absolute value of r and elements of row/col // we use <= or >= in all of these so we are sure of getting // r reset at least once. Real MatrixRowCol::MaximumAbsoluteValue1(Real r, int& i) { REPORT Real* elx = data; int l = storage; int li = -1; while (l--) { Real f = fabs(*elx++); if (r <= f) { r = f; li = l; } } i = (li >= 0) ? storage - li + skip : 0; return r; } // min absolute value of r and elements of row/col Real MatrixRowCol::MinimumAbsoluteValue1(Real r, int& i) { REPORT Real* elx = data; int l = storage; int li = -1; while (l--) { Real f = fabs(*elx++); if (r >= f) { r = f; li = l; } } i = (li >= 0) ? storage - li + skip : 0; return r; } // max value of r and elements of row/col Real MatrixRowCol::Maximum1(Real r, int& i) { REPORT Real* elx = data; int l = storage; int li = -1; while (l--) { Real f = *elx++; if (r <= f) { r = f; li = l; } } i = (li >= 0) ? storage - li + skip : 0; return r; } // min value of r and elements of row/col Real MatrixRowCol::Minimum1(Real r, int& i) { REPORT Real* elx = data; int l = storage; int li = -1; while (l--) { Real f = *elx++; if (r >= f) { r = f; li = l; } } i = (li >= 0) ? storage - li + skip : 0; return r; } Real MatrixRowCol::Sum() { REPORT Real sum = 0.0; Real* elx = data; int l = storage; while (l--) sum += *elx++; return sum; } void MatrixRowCol::SubRowCol(MatrixRowCol& mrc, int skip1, int l1) const { mrc.length = l1; int d = skip - skip1; if (d<0) { mrc.skip = 0; mrc.data = data - d; } else { mrc.skip = d; mrc.data = data; } d = skip + storage - skip1; d = ((l1 < d) ? l1 : d) - mrc.skip; mrc.storage = (d < 0) ? 0 : d; mrc.cw = 0; } #ifdef use_namespace } #endif newmat-1.10.4/newmat3.cpp0000644001161000116100000005753207416507102013374 0ustar rzrrzr//$$ newmat3.cpp Matrix get and restore rows and columns // Copyright (C) 1991,2,3,4: R B Davies //#define WANT_STREAM #include "include.h" #include "newmat.h" #include "newmatrc.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,3); ++ExeCount; } #else #define REPORT {} #endif //#define MONITOR(what,storage,store) // { cout << what << " " << storage << " at " << (long)store << "\n"; } #define MONITOR(what,store,storage) {} // Control bits codes for GetRow, GetCol, RestoreRow, RestoreCol // // LoadOnEntry: // Load data into MatrixRow or Col dummy array under GetRow or GetCol // StoreOnExit: // Restore data to original matrix under RestoreRow or RestoreCol // DirectPart: // Load or restore only part directly stored; must be set with StoreOnExit // Still have decide how to handle this with symmetric // StoreHere: // used in columns only - store data at supplied storage address; // used for GetCol, NextCol & RestoreCol. No need to fill out zeros // HaveStore: // dummy array has been assigned (internal use only). // For symmetric matrices, treat columns as rows unless StoreHere is set; // then stick to columns as this will give better performance for doing // inverses // How components are used: // Use rows wherever possible in preference to columns // Columns without StoreHere are used in in-exact transpose, sum column, // multiply a column vector, and maybe in future access to column, // additional multiply functions, add transpose // Columns with StoreHere are used in exact transpose (not symmetric matrices // or vectors, load only) // Columns with MatrixColX (Store to full column) are used in inverse and solve // Functions required for each matrix class // GetRow(MatrixRowCol& mrc) // GetCol(MatrixRowCol& mrc) // GetCol(MatrixColX& mrc) // RestoreRow(MatrixRowCol& mrc) // RestoreCol(MatrixRowCol& mrc) // RestoreCol(MatrixColX& mrc) // NextRow(MatrixRowCol& mrc) // NextCol(MatrixRowCol& mrc) // NextCol(MatrixColX& mrc) // The Restore routines assume StoreOnExit has already been checked // Defaults for the Next routines are given below // Assume cannot have both !DirectPart && StoreHere for MatrixRowCol routines // Default NextRow and NextCol: // will work as a default but need to override NextRow for efficiency void GeneralMatrix::NextRow(MatrixRowCol& mrc) { REPORT if (+(mrc.cw*StoreOnExit)) { REPORT this->RestoreRow(mrc); } mrc.rowcol++; if (mrc.rowcolGetRow(mrc); } else { REPORT mrc.cw -= StoreOnExit; } } void GeneralMatrix::NextCol(MatrixRowCol& mrc) { REPORT // 423 if (+(mrc.cw*StoreOnExit)) { REPORT this->RestoreCol(mrc); } mrc.rowcol++; if (mrc.rowcolGetCol(mrc); } else { REPORT mrc.cw -= StoreOnExit; } } void GeneralMatrix::NextCol(MatrixColX& mrc) { REPORT // 423 if (+(mrc.cw*StoreOnExit)) { REPORT this->RestoreCol(mrc); } mrc.rowcol++; if (mrc.rowcolGetCol(mrc); } else { REPORT mrc.cw -= StoreOnExit; } } // routines for matrix void Matrix::GetRow(MatrixRowCol& mrc) { REPORT mrc.skip=0; mrc.storage=mrc.length=ncols; mrc.data=store+mrc.rowcol*ncols; } void Matrix::GetCol(MatrixRowCol& mrc) { REPORT mrc.skip=0; mrc.storage=mrc.length=nrows; if ( ncols==1 && !(mrc.cw*StoreHere) ) // ColumnVector { REPORT mrc.data=store; } else { Real* ColCopy; if ( !(mrc.cw*(HaveStore+StoreHere)) ) { REPORT ColCopy = new Real [nrows]; MatrixErrorNoSpace(ColCopy); MONITOR_REAL_NEW("Make (MatGetCol)",nrows,ColCopy) mrc.data = ColCopy; mrc.cw += HaveStore; } else { REPORT ColCopy = mrc.data; } if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+mrc.rowcol; int i=nrows; //while (i--) { *ColCopy++ = *Mstore; Mstore+=ncols; } if (i) for (;;) { *ColCopy++ = *Mstore; if (!(--i)) break; Mstore+=ncols; } } } } void Matrix::GetCol(MatrixColX& mrc) { REPORT mrc.skip=0; mrc.storage=nrows; mrc.length=nrows; if (+(mrc.cw*LoadOnEntry)) { REPORT Real* ColCopy = mrc.data; Real* Mstore = store+mrc.rowcol; int i=nrows; //while (i--) { *ColCopy++ = *Mstore; Mstore+=ncols; } if (i) for (;;) { *ColCopy++ = *Mstore; if (!(--i)) break; Mstore+=ncols; } } } void Matrix::RestoreCol(MatrixRowCol& mrc) { // always check StoreOnExit before calling RestoreCol REPORT // 429 if (+(mrc.cw*HaveStore)) { REPORT // 426 Real* Mstore = store+mrc.rowcol; int i=nrows; Real* Cstore = mrc.data; // while (i--) { *Mstore = *Cstore++; Mstore+=ncols; } if (i) for (;;) { *Mstore = *Cstore++; if (!(--i)) break; Mstore+=ncols; } } } void Matrix::RestoreCol(MatrixColX& mrc) { REPORT Real* Mstore = store+mrc.rowcol; int i=nrows; Real* Cstore = mrc.data; // while (i--) { *Mstore = *Cstore++; Mstore+=ncols; } if (i) for (;;) { *Mstore = *Cstore++; if (!(--i)) break; Mstore+=ncols; } } void Matrix::NextRow(MatrixRowCol& mrc) { REPORT mrc.IncrMat(); } // 1808 void Matrix::NextCol(MatrixRowCol& mrc) { REPORT // 632 if (+(mrc.cw*StoreOnExit)) { REPORT RestoreCol(mrc); } mrc.rowcol++; if (mrc.rowcol= LoadOnEntry) { REPORT *(mrc.data) = *(store+mrc.rowcol); } } void RowVector::NextCol(MatrixRowCol& mrc) { REPORT mrc.rowcol++; mrc.data++; } void RowVector::NextCol(MatrixColX& mrc) { if (+(mrc.cw*StoreOnExit)) { REPORT *(store+mrc.rowcol)=*(mrc.data); } mrc.rowcol++; if (mrc.rowcol < ncols) { if (+(mrc.cw*LoadOnEntry)) { REPORT *(mrc.data)=*(store+mrc.rowcol); } } else { REPORT mrc.cw -= StoreOnExit; } } void RowVector::RestoreCol(MatrixColX& mrc) { REPORT *(store+mrc.rowcol)=*(mrc.data); } // not accessed // routines for band matrices void BandMatrix::GetRow(MatrixRowCol& mrc) { REPORT int r = mrc.rowcol; int w = lower+1+upper; mrc.length=ncols; int s = r-lower; if (s<0) { mrc.data = store+(r*w-s); w += s; s = 0; } else mrc.data = store+r*w; mrc.skip = s; s += w-ncols; if (s>0) w -= s; mrc.storage = w; } // should make special versions of this for upper and lower band matrices void BandMatrix::NextRow(MatrixRowCol& mrc) { REPORT int r = ++mrc.rowcol; if (r<=lower) { mrc.storage++; mrc.data += lower+upper; } else { mrc.skip++; mrc.data += lower+upper+1; } if (r>=ncols-upper) mrc.storage--; } void BandMatrix::GetCol(MatrixRowCol& mrc) { REPORT int c = mrc.rowcol; int n = lower+upper; int w = n+1; mrc.length=nrows; Real* ColCopy; int b; int s = c-upper; if (s<=0) { w += s; s = 0; b = c+lower; } else b = s*w+n; mrc.skip = s; s += w-nrows; if (s>0) w -= s; mrc.storage = w; if ( +(mrc.cw*(StoreHere+HaveStore)) ) { REPORT ColCopy = mrc.data; } else { REPORT ColCopy = new Real [n+1]; MatrixErrorNoSpace(ColCopy); MONITOR_REAL_NEW("Make (BMGetCol)",n+1,ColCopy) mrc.cw += HaveStore; mrc.data = ColCopy; } if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+b; // while (w--) { *ColCopy++ = *Mstore; Mstore+=n; } if (w) for (;;) { *ColCopy++ = *Mstore; if (!(--w)) break; Mstore+=n; } } } void BandMatrix::GetCol(MatrixColX& mrc) { REPORT int c = mrc.rowcol; int n = lower+upper; int w = n+1; mrc.length=nrows; int b; int s = c-upper; if (s<=0) { w += s; s = 0; b = c+lower; } else b = s*w+n; mrc.skip = s; s += w-nrows; if (s>0) w -= s; mrc.storage = w; mrc.data = mrc.store+mrc.skip; if (+(mrc.cw*LoadOnEntry)) { REPORT Real* ColCopy = mrc.data; Real* Mstore = store+b; // while (w--) { *ColCopy++ = *Mstore; Mstore+=n; } if (w) for (;;) { *ColCopy++ = *Mstore; if (!(--w)) break; Mstore+=n; } } } void BandMatrix::RestoreCol(MatrixRowCol& mrc) { REPORT int c = mrc.rowcol; int n = lower+upper; int s = c-upper; Real* Mstore = store + ((s<=0) ? c+lower : s*n+s+n); Real* Cstore = mrc.data; int w = mrc.storage; // while (w--) { *Mstore = *Cstore++; Mstore += n; } if (w) for (;;) { *Mstore = *Cstore++; if (!(--w)) break; Mstore += n; } } // routines for symmetric band matrix void SymmetricBandMatrix::GetRow(MatrixRowCol& mrc) { REPORT int r=mrc.rowcol; int s = r-lower; int w1 = lower+1; int o = r*w1; mrc.length = ncols; if (s<0) { w1 += s; o -= s; s = 0; } mrc.skip = s; if (+(mrc.cw*DirectPart)) { REPORT mrc.data = store+o; mrc.storage = w1; } else { // do not allow StoreOnExit and !DirectPart if (+(mrc.cw*StoreOnExit)) Throw(InternalException("SymmetricBandMatrix::GetRow(MatrixRowCol&)")); int w = w1+lower; s += w-ncols; Real* RowCopy; if (s>0) w -= s; mrc.storage = w; int w2 = w-w1; if (!(mrc.cw*HaveStore)) { REPORT RowCopy = new Real [2*lower+1]; MatrixErrorNoSpace(RowCopy); MONITOR_REAL_NEW("Make (SmBGetRow)",2*lower+1,RowCopy) mrc.cw += HaveStore; mrc.data = RowCopy; } else { REPORT RowCopy = mrc.data; } if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+o; while (w1--) *RowCopy++ = *Mstore++; Mstore--; while (w2--) { Mstore += lower; *RowCopy++ = *Mstore; } } } } void SymmetricBandMatrix::GetCol(MatrixRowCol& mrc) { // do not allow StoreHere if (+(mrc.cw*StoreHere)) Throw(InternalException("SymmetricBandMatrix::GetCol(MatrixRowCol&)")); int c=mrc.rowcol; int w1 = lower+1; mrc.length=nrows; REPORT int s = c-lower; int o = c*w1; if (s<0) { w1 += s; o -= s; s = 0; } mrc.skip = s; if (+(mrc.cw*DirectPart)) { REPORT mrc.data = store+o; mrc.storage = w1; } else { // do not allow StoreOnExit and !DirectPart if (+(mrc.cw*StoreOnExit)) Throw(InternalException("SymmetricBandMatrix::GetCol(MatrixRowCol&)")); int w = w1+lower; s += w-ncols; Real* ColCopy; if (s>0) w -= s; mrc.storage = w; int w2 = w-w1; if ( +(mrc.cw*HaveStore) ) { REPORT ColCopy = mrc.data; } else { REPORT ColCopy = new Real [2*lower+1]; MatrixErrorNoSpace(ColCopy); MONITOR_REAL_NEW("Make (SmBGetCol)",2*lower+1,ColCopy) mrc.cw += HaveStore; mrc.data = ColCopy; } if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+o; while (w1--) *ColCopy++ = *Mstore++; Mstore--; while (w2--) { Mstore += lower; *ColCopy++ = *Mstore; } } } } void SymmetricBandMatrix::GetCol(MatrixColX& mrc) { int c=mrc.rowcol; int w1 = lower+1; mrc.length=nrows; if (+(mrc.cw*DirectPart)) { REPORT int b = c*w1+lower; mrc.skip = c; c += w1-nrows; w1 -= c; mrc.storage = w1; Real* ColCopy = mrc.data = mrc.store+mrc.skip; if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+b; // while (w1--) { *ColCopy++ = *Mstore; Mstore += lower; } if (w1) for (;;) { *ColCopy++ = *Mstore; if (!(--w1)) break; Mstore += lower; } } } else { REPORT // do not allow StoreOnExit and !DirectPart if (+(mrc.cw*StoreOnExit)) Throw(InternalException("SymmetricBandMatrix::GetCol(MatrixColX&)")); int s = c-lower; int o = c*w1; if (s<0) { w1 += s; o -= s; s = 0; } mrc.skip = s; int w = w1+lower; s += w-ncols; if (s>0) w -= s; mrc.storage = w; int w2 = w-w1; Real* ColCopy = mrc.data = mrc.store+mrc.skip; if (+(mrc.cw*LoadOnEntry)) { REPORT Real* Mstore = store+o; while (w1--) *ColCopy++ = *Mstore++; Mstore--; while (w2--) { Mstore += lower; *ColCopy++ = *Mstore; } } } } void SymmetricBandMatrix::RestoreCol(MatrixColX& mrc) { REPORT int c = mrc.rowcol; Real* Mstore = store + c*lower+c+lower; Real* Cstore = mrc.data; int w = mrc.storage; // while (w--) { *Mstore = *Cstore++; Mstore += lower; } if (w) for (;;) { *Mstore = *Cstore++; if (!(--w)) break; Mstore += lower; } } // routines for identity matrix void IdentityMatrix::GetRow(MatrixRowCol& mrc) { REPORT mrc.skip=mrc.rowcol; mrc.storage=1; mrc.data=store; mrc.length=ncols; } void IdentityMatrix::GetCol(MatrixRowCol& mrc) { REPORT mrc.skip=mrc.rowcol; mrc.storage=1; mrc.length=nrows; if (+(mrc.cw*StoreHere)) // should not happen Throw(InternalException("IdentityMatrix::GetCol(MatrixRowCol&)")); else { REPORT mrc.data=store; } } void IdentityMatrix::GetCol(MatrixColX& mrc) { REPORT mrc.skip=mrc.rowcol; mrc.storage=1; mrc.length=nrows; mrc.data = mrc.store+mrc.skip; *(mrc.data)=*store; } void IdentityMatrix::NextRow(MatrixRowCol& mrc) { REPORT mrc.IncrId(); } void IdentityMatrix::NextCol(MatrixRowCol& mrc) { REPORT mrc.IncrId(); } void IdentityMatrix::NextCol(MatrixColX& mrc) { REPORT if (+(mrc.cw*StoreOnExit)) { REPORT *store=*(mrc.data); } mrc.IncrDiag(); // must increase mrc.data so need IncrDiag int t1 = +(mrc.cw*LoadOnEntry); if (t1 && mrc.rowcol < ncols) { REPORT *(mrc.data)=*store; } } // *************************** destructors ******************************* MatrixRowCol::~MatrixRowCol() { if (+(cw*HaveStore)) { MONITOR_REAL_DELETE("Free (RowCol)",-1,data) // do not know length delete [] data; } } MatrixRow::~MatrixRow() { if (+(cw*StoreOnExit)) gm->RestoreRow(*this); } MatrixCol::~MatrixCol() { if (+(cw*StoreOnExit)) gm->RestoreCol(*this); } MatrixColX::~MatrixColX() { if (+(cw*StoreOnExit)) gm->RestoreCol(*this); } #ifdef use_namespace } #endif newmat-1.10.4/newmat4.cpp0000644001161000116100000006006507647677240013411 0ustar rzrrzr//$$ newmat4.cpp Constructors, ReSize, basic utilities // Copyright (C) 1991,2,3,4,8,9: R B Davies #include "include.h" #include "newmat.h" #include "newmatrc.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,4); ++ExeCount; } #else #define REPORT {} #endif #define DO_SEARCH // search for LHS of = in RHS // ************************* general utilities *************************/ static int tristore(int n) // elements in triangular matrix { return (n*(n+1))/2; } // **************************** constructors ***************************/ GeneralMatrix::GeneralMatrix() { store=0; storage=0; nrows=0; ncols=0; tag=-1; } GeneralMatrix::GeneralMatrix(ArrayLengthSpecifier s) { REPORT storage=s.Value(); tag=-1; if (storage) { store = new Real [storage]; MatrixErrorNoSpace(store); MONITOR_REAL_NEW("Make (GenMatrix)",storage,store) } else store = 0; } Matrix::Matrix(int m, int n) : GeneralMatrix(m*n) { REPORT nrows=m; ncols=n; } SymmetricMatrix::SymmetricMatrix(ArrayLengthSpecifier n) : GeneralMatrix(tristore(n.Value())) { REPORT nrows=n.Value(); ncols=n.Value(); } UpperTriangularMatrix::UpperTriangularMatrix(ArrayLengthSpecifier n) : GeneralMatrix(tristore(n.Value())) { REPORT nrows=n.Value(); ncols=n.Value(); } LowerTriangularMatrix::LowerTriangularMatrix(ArrayLengthSpecifier n) : GeneralMatrix(tristore(n.Value())) { REPORT nrows=n.Value(); ncols=n.Value(); } DiagonalMatrix::DiagonalMatrix(ArrayLengthSpecifier m) : GeneralMatrix(m) { REPORT nrows=m.Value(); ncols=m.Value(); } Matrix::Matrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Rt); GetMatrix(gmx); } RowVector::RowVector(const BaseMatrix& M) : Matrix(M) { if (nrows!=1) { Tracer tr("RowVector"); Throw(VectorException(*this)); } } ColumnVector::ColumnVector(const BaseMatrix& M) : Matrix(M) { if (ncols!=1) { Tracer tr("ColumnVector"); Throw(VectorException(*this)); } } SymmetricMatrix::SymmetricMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Sm); GetMatrix(gmx); } UpperTriangularMatrix::UpperTriangularMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::UT); GetMatrix(gmx); } LowerTriangularMatrix::LowerTriangularMatrix(const BaseMatrix& M) { REPORT // CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::LT); GetMatrix(gmx); } DiagonalMatrix::DiagonalMatrix(const BaseMatrix& M) { REPORT //CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Dg); GetMatrix(gmx); } IdentityMatrix::IdentityMatrix(const BaseMatrix& M) { REPORT //CheckConversion(M); // MatrixConversionCheck mcc; GeneralMatrix* gmx=((BaseMatrix&)M).Evaluate(MatrixType::Id); GetMatrix(gmx); } GeneralMatrix::~GeneralMatrix() { if (store) { MONITOR_REAL_DELETE("Free (GenMatrix)",storage,store) delete [] store; } } CroutMatrix::CroutMatrix(const BaseMatrix& m) { REPORT Tracer tr("CroutMatrix"); indx = 0; // in case of exception at next line GeneralMatrix* gm = ((BaseMatrix&)m).Evaluate(MatrixType::Rt); GetMatrix(gm); if (nrows!=ncols) { CleanUp(); Throw(NotSquareException(*gm)); } d=true; sing=false; indx=new int [nrows]; MatrixErrorNoSpace(indx); MONITOR_INT_NEW("Index (CroutMat)",nrows,indx) ludcmp(); } CroutMatrix::~CroutMatrix() { MONITOR_INT_DELETE("Index (CroutMat)",nrows,indx) delete [] indx; } //ReturnMatrixX::ReturnMatrixX(GeneralMatrix& gmx) //{ // REPORT // gm = gmx.Image(); gm->ReleaseAndDelete(); //} #ifndef TEMPS_DESTROYED_QUICKLY_R GeneralMatrix::operator ReturnMatrixX() const { REPORT GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); return ReturnMatrixX(gm); } #else GeneralMatrix::operator ReturnMatrixX&() const { REPORT GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); ReturnMatrixX* x = new ReturnMatrixX(gm); MatrixErrorNoSpace(x); return *x; } #endif #ifndef TEMPS_DESTROYED_QUICKLY_R ReturnMatrixX GeneralMatrix::ForReturn() const { REPORT GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); return ReturnMatrixX(gm); } #else ReturnMatrixX& GeneralMatrix::ForReturn() const { REPORT GeneralMatrix* gm = Image(); gm->ReleaseAndDelete(); ReturnMatrixX* x = new ReturnMatrixX(gm); MatrixErrorNoSpace(x); return *x; } #endif // ************************** ReSize matrices ***************************/ void GeneralMatrix::ReSize(int nr, int nc, int s) { REPORT if (store) { MONITOR_REAL_DELETE("Free (ReDimensi)",storage,store) delete [] store; } storage=s; nrows=nr; ncols=nc; tag=-1; if (s) { store = new Real [storage]; MatrixErrorNoSpace(store); MONITOR_REAL_NEW("Make (ReDimensi)",storage,store) } else store = 0; } void Matrix::ReSize(int nr, int nc) { REPORT GeneralMatrix::ReSize(nr,nc,nr*nc); } void SymmetricMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,tristore(nr)); } void UpperTriangularMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,tristore(nr)); } void LowerTriangularMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,tristore(nr)); } void DiagonalMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,nr); } void RowVector::ReSize(int nc) { REPORT GeneralMatrix::ReSize(1,nc,nc); } void ColumnVector::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,1,nr); } void RowVector::ReSize(int nr, int nc) { Tracer tr("RowVector::ReSize"); if (nr != 1) Throw(VectorException(*this)); REPORT GeneralMatrix::ReSize(1,nc,nc); } void ColumnVector::ReSize(int nr, int nc) { Tracer tr("ColumnVector::ReSize"); if (nc != 1) Throw(VectorException(*this)); REPORT GeneralMatrix::ReSize(nr,1,nr); } void IdentityMatrix::ReSize(int nr) { REPORT GeneralMatrix::ReSize(nr,nr,1); *store = 1; } void Matrix::ReSize(const GeneralMatrix& A) { REPORT ReSize(A.Nrows(), A.Ncols()); } void nricMatrix::ReSize(const GeneralMatrix& A) { REPORT ReSize(A.Nrows(), A.Ncols()); } void ColumnVector::ReSize(const GeneralMatrix& A) { REPORT ReSize(A.Nrows(), A.Ncols()); } void RowVector::ReSize(const GeneralMatrix& A) { REPORT ReSize(A.Nrows(), A.Ncols()); } void SymmetricMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("SymmetricMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void DiagonalMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("DiagonalMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void UpperTriangularMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("UpperTriangularMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void LowerTriangularMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("LowerTriangularMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void IdentityMatrix::ReSize(const GeneralMatrix& A) { REPORT int n = A.Nrows(); if (n != A.Ncols()) { Tracer tr("IdentityMatrix::ReSize(GM)"); Throw(NotSquareException(*this)); } ReSize(n); } void GeneralMatrix::ReSize(const GeneralMatrix&) { REPORT Tracer tr("GeneralMatrix::ReSize(GM)"); Throw(NotDefinedException("ReSize", "this type of matrix")); } void GeneralMatrix::ReSizeForAdd(const GeneralMatrix& A, const GeneralMatrix&) { REPORT ReSize(A); } void GeneralMatrix::ReSizeForSP(const GeneralMatrix& A, const GeneralMatrix&) { REPORT ReSize(A); } // ************************* SameStorageType ******************************/ // SameStorageType checks A and B have same storage type including bandwidth // It does not check same dimensions since we assume this is already done bool GeneralMatrix::SameStorageType(const GeneralMatrix& A) const { REPORT return Type() == A.Type(); } // ******************* manipulate types, storage **************************/ int GeneralMatrix::search(const BaseMatrix* s) const { REPORT return (s==this) ? 1 : 0; } int GenericMatrix::search(const BaseMatrix* s) const { REPORT return gm->search(s); } int MultipliedMatrix::search(const BaseMatrix* s) const { REPORT return bm1->search(s) + bm2->search(s); } int ShiftedMatrix::search(const BaseMatrix* s) const { REPORT return bm->search(s); } int NegatedMatrix::search(const BaseMatrix* s) const { REPORT return bm->search(s); } int ReturnMatrixX::search(const BaseMatrix* s) const { REPORT return (s==gm) ? 1 : 0; } MatrixType Matrix::Type() const { return MatrixType::Rt; } MatrixType SymmetricMatrix::Type() const { return MatrixType::Sm; } MatrixType UpperTriangularMatrix::Type() const { return MatrixType::UT; } MatrixType LowerTriangularMatrix::Type() const { return MatrixType::LT; } MatrixType DiagonalMatrix::Type() const { return MatrixType::Dg; } MatrixType RowVector::Type() const { return MatrixType::RV; } MatrixType ColumnVector::Type() const { return MatrixType::CV; } MatrixType CroutMatrix::Type() const { return MatrixType::Ct; } MatrixType BandMatrix::Type() const { return MatrixType::BM; } MatrixType UpperBandMatrix::Type() const { return MatrixType::UB; } MatrixType LowerBandMatrix::Type() const { return MatrixType::LB; } MatrixType SymmetricBandMatrix::Type() const { return MatrixType::SB; } MatrixType IdentityMatrix::Type() const { return MatrixType::Id; } MatrixBandWidth BaseMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth DiagonalMatrix::BandWidth() const { REPORT return 0; } MatrixBandWidth IdentityMatrix::BandWidth() const { REPORT return 0; } MatrixBandWidth UpperTriangularMatrix::BandWidth() const { REPORT return MatrixBandWidth(0,-1); } MatrixBandWidth LowerTriangularMatrix::BandWidth() const { REPORT return MatrixBandWidth(-1,0); } MatrixBandWidth BandMatrix::BandWidth() const { REPORT return MatrixBandWidth(lower,upper); } MatrixBandWidth GenericMatrix::BandWidth()const { REPORT return gm->BandWidth(); } MatrixBandWidth AddedMatrix::BandWidth() const { REPORT return gm1->BandWidth() + gm2->BandWidth(); } MatrixBandWidth SPMatrix::BandWidth() const { REPORT return gm1->BandWidth().minimum(gm2->BandWidth()); } MatrixBandWidth KPMatrix::BandWidth() const { int lower, upper; MatrixBandWidth bw1 = gm1->BandWidth(), bw2 = gm2->BandWidth(); if (bw1.Lower() < 0) { if (bw2.Lower() < 0) { REPORT lower = -1; } else { REPORT lower = bw2.Lower() + (gm1->Nrows() - 1) * gm2->Nrows(); } } else { if (bw2.Lower() < 0) { REPORT lower = (1 + bw1.Lower()) * gm2->Nrows() - 1; } else { REPORT lower = bw2.Lower() + bw1.Lower() * gm2->Nrows(); } } if (bw1.Upper() < 0) { if (bw2.Upper() < 0) { REPORT upper = -1; } else { REPORT upper = bw2.Upper() + (gm1->Nrows() - 1) * gm2->Nrows(); } } else { if (bw2.Upper() < 0) { REPORT upper = (1 + bw1.Upper()) * gm2->Nrows() - 1; } else { REPORT upper = bw2.Upper() + bw1.Upper() * gm2->Nrows(); } } return MatrixBandWidth(lower, upper); } MatrixBandWidth MultipliedMatrix::BandWidth() const { REPORT return gm1->BandWidth() * gm2->BandWidth(); } MatrixBandWidth ConcatenatedMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth SolvedMatrix::BandWidth() const { if (+gm1->Type() & MatrixType::Diagonal) { REPORT return gm2->BandWidth(); } else { REPORT return -1; } } MatrixBandWidth ScaledMatrix::BandWidth() const { REPORT return gm->BandWidth(); } MatrixBandWidth NegatedMatrix::BandWidth() const { REPORT return gm->BandWidth(); } MatrixBandWidth TransposedMatrix::BandWidth() const { REPORT return gm->BandWidth().t(); } MatrixBandWidth InvertedMatrix::BandWidth() const { if (+gm->Type() & MatrixType::Diagonal) { REPORT return MatrixBandWidth(0,0); } else { REPORT return -1; } } MatrixBandWidth RowedMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth ColedMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth DiagedMatrix::BandWidth() const { REPORT return 0; } MatrixBandWidth MatedMatrix::BandWidth() const { REPORT return -1; } MatrixBandWidth ReturnMatrixX::BandWidth() const { REPORT return gm->BandWidth(); } MatrixBandWidth GetSubMatrix::BandWidth() const { if (row_skip==col_skip && row_number==col_number) { REPORT return gm->BandWidth(); } else { REPORT return MatrixBandWidth(-1); } } // ********************** the memory managment tools **********************/ // Rules regarding tDelete, reuse, GetStore // All matrices processed during expression evaluation must be subject // to exactly one of reuse(), tDelete(), GetStore() or BorrowStore(). // If reuse returns true the matrix must be reused. // GetMatrix(gm) always calls gm->GetStore() // gm->Evaluate obeys rules // bm->Evaluate obeys rules for matrices in bm structure void GeneralMatrix::tDelete() { if (tag<0) { if (tag<-1) { REPORT store=0; delete this; return; } // borrowed else { REPORT return; } } if (tag==1) { if (store) { REPORT MONITOR_REAL_DELETE("Free (tDelete)",storage,store) delete [] store; } store=0; CleanUp(); tag=-1; return; } if (tag==0) { REPORT delete this; return; } REPORT tag--; return; } static void BlockCopy(int n, Real* from, Real* to) { REPORT int i = (n >> 3); while (i--) { *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; *to++ = *from++; } i = n & 7; while (i--) *to++ = *from++; } bool GeneralMatrix::reuse() { if (tag<-1) { if (storage) { REPORT Real* s = new Real [storage]; MatrixErrorNoSpace(s); MONITOR_REAL_NEW("Make (reuse)",storage,s) BlockCopy(storage, store, s); store=s; } else { REPORT store = 0; CleanUp(); } tag=0; return true; } if (tag<0) { REPORT return false; } if (tag<=1) { REPORT return true; } REPORT tag--; return false; } Real* GeneralMatrix::GetStore() { if (tag<0 || tag>1) { Real* s; if (storage) { s = new Real [storage]; MatrixErrorNoSpace(s); MONITOR_REAL_NEW("Make (GetStore)",storage,s) BlockCopy(storage, store, s); } else s = 0; if (tag>1) { REPORT tag--; } else if (tag < -1) { REPORT store=0; delete this; } // borrowed store else { REPORT } return s; } Real* s=store; store=0; if (tag==0) { REPORT delete this; } else { REPORT CleanUp(); tag=-1; } return s; } void GeneralMatrix::GetMatrix(const GeneralMatrix* gmx) { REPORT tag=-1; nrows=gmx->Nrows(); ncols=gmx->Ncols(); storage=gmx->storage; SetParameters(gmx); store=((GeneralMatrix*)gmx)->GetStore(); } GeneralMatrix* GeneralMatrix::BorrowStore(GeneralMatrix* gmx, MatrixType mt) // Copy storage of *this to storage of *gmx. Then convert to type mt. // If mt == 0 just let *gmx point to storage of *this if tag==-1. { if (!mt) { if (tag == -1) { REPORT gmx->tag = -2; gmx->store = store; } else { REPORT gmx->tag = 0; gmx->store = GetStore(); } } else if (Compare(gmx->Type(),mt)) { REPORT gmx->tag = 0; gmx->store = GetStore(); } else { REPORT gmx->tag = -2; gmx->store = store; gmx = gmx->Evaluate(mt); gmx->tag = 0; tDelete(); } return gmx; } void GeneralMatrix::Eq(const BaseMatrix& X, MatrixType mt) // Count number of references to this in X. // If zero delete storage in this; // otherwise tag this to show when storage can be deleted // evaluate X and copy to this { #ifdef DO_SEARCH int counter=X.search(this); if (counter==0) { REPORT if (store) { MONITOR_REAL_DELETE("Free (operator=)",storage,store) REPORT delete [] store; storage=0; store = 0; } } else { REPORT Release(counter); } GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(mt); if (gmx!=this) { REPORT GetMatrix(gmx); } else { REPORT } Protect(); #else GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(mt); if (gmx!=this) { REPORT if (store) { MONITOR_REAL_DELETE("Free (operator=)",storage,store) REPORT delete [] store; storage=0; store = 0; } GetMatrix(gmx); } else { REPORT } Protect(); #endif } // version to work with operator<< void GeneralMatrix::Eq(const BaseMatrix& X, MatrixType mt, bool ldok) { REPORT if (ldok) mt.SetDataLossOK(); Eq(X, mt); } void GeneralMatrix::Eq2(const BaseMatrix& X, MatrixType mt) // a cut down version of Eq for use with += etc. // we know BaseMatrix points to two GeneralMatrix objects, // the first being this (may be the same). // we know tag has been set correctly in each. { GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(mt); if (gmx!=this) { REPORT GetMatrix(gmx); } // simplify GetMatrix ? else { REPORT } Protect(); } void GeneralMatrix::Inject(const GeneralMatrix& X) // copy stored values of X; otherwise leave els of *this unchanged { REPORT Tracer tr("Inject"); if (nrows != X.nrows || ncols != X.ncols) Throw(IncompatibleDimensionsException()); MatrixRow mr((GeneralMatrix*)&X, LoadOnEntry); MatrixRow mrx(this, LoadOnEntry+StoreOnExit+DirectPart); int i=nrows; while (i--) { mrx.Inject(mr); mrx.Next(); mr.Next(); } } // ************* checking for data loss during conversion *******************/ bool Compare(const MatrixType& source, MatrixType& destination) { if (!destination) { destination=source; return true; } if (destination==source) return true; if (!destination.DataLossOK && !(destination>=source)) Throw(ProgramException("Illegal Conversion", source, destination)); return false; } // ************* Make a copy of a matrix on the heap *********************/ GeneralMatrix* Matrix::Image() const { REPORT GeneralMatrix* gm = new Matrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* SymmetricMatrix::Image() const { REPORT GeneralMatrix* gm = new SymmetricMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* UpperTriangularMatrix::Image() const { REPORT GeneralMatrix* gm = new UpperTriangularMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* LowerTriangularMatrix::Image() const { REPORT GeneralMatrix* gm = new LowerTriangularMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* DiagonalMatrix::Image() const { REPORT GeneralMatrix* gm = new DiagonalMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* RowVector::Image() const { REPORT GeneralMatrix* gm = new RowVector(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* ColumnVector::Image() const { REPORT GeneralMatrix* gm = new ColumnVector(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* BandMatrix::Image() const { REPORT GeneralMatrix* gm = new BandMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* UpperBandMatrix::Image() const { REPORT GeneralMatrix* gm = new UpperBandMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* LowerBandMatrix::Image() const { REPORT GeneralMatrix* gm = new LowerBandMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* SymmetricBandMatrix::Image() const { REPORT GeneralMatrix* gm = new SymmetricBandMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* nricMatrix::Image() const { REPORT GeneralMatrix* gm = new nricMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* IdentityMatrix::Image() const { REPORT GeneralMatrix* gm = new IdentityMatrix(*this); MatrixErrorNoSpace(gm); return gm; } GeneralMatrix* GeneralMatrix::Image() const { bool dummy = true; if (dummy) // get rid of warning message Throw(InternalException("Cannot apply Image to this matrix type")); return 0; } // *********************** nricMatrix routines *****************************/ void nricMatrix::MakeRowPointer() { if (nrows > 0) { row_pointer = new Real* [nrows]; MatrixErrorNoSpace(row_pointer); Real* s = Store() - 1; int i = nrows; Real** rp = row_pointer; if (i) for (;;) { *rp++ = s; if (!(--i)) break; s+=ncols; } } else row_pointer = 0; } void nricMatrix::DeleteRowPointer() { if (nrows) delete [] row_pointer; } void GeneralMatrix::CheckStore() const { if (!store) Throw(ProgramException("NRIC accessing matrix with unset dimensions")); } // *************************** CleanUp routines *****************************/ void GeneralMatrix::CleanUp() { // set matrix dimensions to zero, delete storage REPORT if (store && storage) { MONITOR_REAL_DELETE("Free (CleanUp) ",storage,store) REPORT delete [] store; } store=0; storage=0; nrows=0; ncols=0; } void nricMatrix::CleanUp() { DeleteRowPointer(); GeneralMatrix::CleanUp(); } void RowVector::CleanUp() { GeneralMatrix::CleanUp(); nrows=1; } void ColumnVector::CleanUp() { GeneralMatrix::CleanUp(); ncols=1; } void CroutMatrix::CleanUp() { if (nrows) delete [] indx; GeneralMatrix::CleanUp(); } void BandLUMatrix::CleanUp() { if (nrows) delete [] indx; if (storage2) delete [] store2; GeneralMatrix::CleanUp(); } // ************************ simple integer array class *********************** // construct a new array of length xn. Check that xn is non-negative and // that space is available SimpleIntArray::SimpleIntArray(int xn) : n(xn) { if (n < 0) Throw(Logic_error("invalid array length")); else if (n == 0) { REPORT a = 0; } else { REPORT a = new int [n]; if (!a) Throw(Bad_alloc()); } } // destroy an array - return its space to memory SimpleIntArray::~SimpleIntArray() { REPORT if (a) delete [] a; } // access an element of an array; return a "reference" so elements // can be modified. // check index is within range // in this array class the index runs from 0 to n-1 int& SimpleIntArray::operator[](int i) { REPORT if (i < 0 || i >= n) Throw(Logic_error("array index out of range")); return a[i]; } // same thing again but for arrays declared constant so we can't // modify its elements int SimpleIntArray::operator[](int i) const { REPORT if (i < 0 || i >= n) Throw(Logic_error("array index out of range")); return a[i]; } // set all the elements equal to a given value void SimpleIntArray::operator=(int ai) { REPORT for (int i = 0; i < n; i++) a[i] = ai; } // set the elements equal to those of another array. // check the arrays are of the same length void SimpleIntArray::operator=(const SimpleIntArray& b) { REPORT if (b.n != n) Throw(Logic_error("array lengths differ in copy")); for (int i = 0; i < n; i++) a[i] = b.a[i]; } // construct a new array equal to an existing array // check that space is available SimpleIntArray::SimpleIntArray(const SimpleIntArray& b) : n(b.n) { if (n == 0) { REPORT a = 0; } else { REPORT a = new int [n]; if (!a) Throw(Bad_alloc()); for (int i = 0; i < n; i++) a[i] = b.a[i]; } } // change the size of an array; optionally copy data from old array to // new array void SimpleIntArray::ReSize(int n1, bool keep) { if (n1 == n) { REPORT return; } else if (n1 == 0) { REPORT n = 0; delete [] a; a = 0; } else if (n == 0) { REPORT a = new int [n1]; if (!a) Throw(Bad_alloc()); n = n1; } else { int* a1 = a; if (keep) { REPORT a = new int [n1]; if (!a) Throw(Bad_alloc()); if (n > n1) n = n1; for (int i = 0; i < n; i++) a[i] = a1[i]; n = n1; delete [] a1; } else { REPORT n = n1; delete [] a1; a = new int [n]; if (!a) Throw(Bad_alloc()); } } } #ifdef use_namespace } #endif newmat-1.10.4/newmat5.cpp0000644001161000116100000003426207414476174013405 0ustar rzrrzr//$$ newmat5.cpp Transpose, evaluate etc // Copyright (C) 1991,2,3,4: R B Davies //#define WANT_STREAM #include "include.h" #include "newmat.h" #include "newmatrc.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,5); ++ExeCount; } #else #define REPORT {} #endif /************************ carry out operations ******************************/ GeneralMatrix* GeneralMatrix::Transpose(TransposedMatrix* tm, MatrixType mt) { GeneralMatrix* gm1; if (Compare(Type().t(),mt)) { REPORT gm1 = mt.New(ncols,nrows,tm); for (int i=0; iReleaseAndDelete(); return gm1; } GeneralMatrix* SymmetricMatrix::Transpose(TransposedMatrix*, MatrixType mt) { REPORT return Evaluate(mt); } GeneralMatrix* DiagonalMatrix::Transpose(TransposedMatrix*, MatrixType mt) { REPORT return Evaluate(mt); } GeneralMatrix* ColumnVector::Transpose(TransposedMatrix*, MatrixType mt) { REPORT GeneralMatrix* gmx = new RowVector; MatrixErrorNoSpace(gmx); gmx->nrows = 1; gmx->ncols = gmx->storage = storage; return BorrowStore(gmx,mt); } GeneralMatrix* RowVector::Transpose(TransposedMatrix*, MatrixType mt) { REPORT GeneralMatrix* gmx = new ColumnVector; MatrixErrorNoSpace(gmx); gmx->ncols = 1; gmx->nrows = gmx->storage = storage; return BorrowStore(gmx,mt); } GeneralMatrix* IdentityMatrix::Transpose(TransposedMatrix*, MatrixType mt) { REPORT return Evaluate(mt); } GeneralMatrix* GeneralMatrix::Evaluate(MatrixType mt) { if (Compare(this->Type(),mt)) { REPORT return this; } REPORT GeneralMatrix* gmx = mt.New(nrows,ncols,this); MatrixRow mr(this, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); int i=nrows; while (i--) { mrx.Copy(mr); mrx.Next(); mr.Next(); } tDelete(); gmx->ReleaseAndDelete(); return gmx; } GeneralMatrix* GenericMatrix::Evaluate(MatrixType mt) { REPORT return gm->Evaluate(mt); } GeneralMatrix* ShiftedMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); int nr=gm->Nrows(); int nc=gm->Ncols(); Compare(gm->Type().AddEqualEl(),mt); if (!(mt==gm->Type())) { REPORT GeneralMatrix* gmx = mt.New(nr,nc,this); MatrixRow mr(gm, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); while (nr--) { mrx.Add(mr,f); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } else if (gm->reuse()) { REPORT gm->Add(f); #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmx = gm; delete this; return gmx; #else return gm; #endif } else { REPORT GeneralMatrix* gmy = gm->Type().New(nr,nc,this); gmy->ReleaseAndDelete(); gmy->Add(gm,f); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmy; } } GeneralMatrix* NegShiftedMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); int nr=gm->Nrows(); int nc=gm->Ncols(); Compare(gm->Type().AddEqualEl(),mt); if (!(mt==gm->Type())) { REPORT GeneralMatrix* gmx = mt.New(nr,nc,this); MatrixRow mr(gm, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); while (nr--) { mrx.NegAdd(mr,f); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } else if (gm->reuse()) { REPORT gm->NegAdd(f); #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmx = gm; delete this; return gmx; #else return gm; #endif } else { REPORT GeneralMatrix* gmy = gm->Type().New(nr,nc,this); gmy->ReleaseAndDelete(); gmy->NegAdd(gm,f); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmy; } } GeneralMatrix* ScaledMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); int nr=gm->Nrows(); int nc=gm->Ncols(); if (Compare(gm->Type(),mt)) { if (gm->reuse()) { REPORT gm->Multiply(f); #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmx = gm; delete this; return gmx; #else return gm; #endif } else { REPORT GeneralMatrix* gmx = gm->Type().New(nr,nc,this); gmx->ReleaseAndDelete(); gmx->Multiply(gm,f); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } } else { REPORT GeneralMatrix* gmx = mt.New(nr,nc,this); MatrixRow mr(gm, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); while (nr--) { mrx.Multiply(mr,f); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } } GeneralMatrix* NegatedMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); int nr=gm->Nrows(); int nc=gm->Ncols(); if (Compare(gm->Type(),mt)) { if (gm->reuse()) { REPORT gm->Negate(); #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmx = gm; delete this; return gmx; #else return gm; #endif } else { REPORT GeneralMatrix* gmx = gm->Type().New(nr,nc,this); gmx->ReleaseAndDelete(); gmx->Negate(gm); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } } else { REPORT GeneralMatrix* gmx = mt.New(nr,nc,this); MatrixRow mr(gm, LoadOnEntry); MatrixRow mrx(gmx, StoreOnExit+DirectPart); while (nr--) { mrx.Negate(mr); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } } GeneralMatrix* ReversedMatrix::Evaluate(MatrixType mt) { gm=((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx; if ((gm->Type()).IsBand() && ! (gm->Type()).IsDiagonal()) { gm->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif Throw(NotDefinedException("Reverse", "band matrices")); } if (gm->reuse()) { REPORT gm->ReverseElements(); gmx = gm; } else { REPORT gmx = gm->Type().New(gm->Nrows(), gm->Ncols(), this); gmx->ReverseElements(gm); gmx->ReleaseAndDelete(); } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx->Evaluate(mt); // target matrix is different type? } GeneralMatrix* TransposedMatrix::Evaluate(MatrixType mt) { REPORT gm=((BaseMatrix*&)bm)->Evaluate(); Compare(gm->Type().t(),mt); GeneralMatrix* gmx=gm->Transpose(this, mt); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } GeneralMatrix* RowedMatrix::Evaluate(MatrixType mt) { gm = ((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx = new RowVector; MatrixErrorNoSpace(gmx); gmx->nrows = 1; gmx->ncols = gmx->storage = gm->storage; #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmy = gm; delete this; return gmy->BorrowStore(gmx,mt); #else return gm->BorrowStore(gmx,mt); #endif } GeneralMatrix* ColedMatrix::Evaluate(MatrixType mt) { gm = ((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx = new ColumnVector; MatrixErrorNoSpace(gmx); gmx->ncols = 1; gmx->nrows = gmx->storage = gm->storage; #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmy = gm; delete this; return gmy->BorrowStore(gmx,mt); #else return gm->BorrowStore(gmx,mt); #endif } GeneralMatrix* DiagedMatrix::Evaluate(MatrixType mt) { gm = ((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx = new DiagonalMatrix; MatrixErrorNoSpace(gmx); gmx->nrows = gmx->ncols = gmx->storage = gm->storage; #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmy = gm; delete this; return gmy->BorrowStore(gmx,mt); #else return gm->BorrowStore(gmx,mt); #endif } GeneralMatrix* MatedMatrix::Evaluate(MatrixType mt) { Tracer tr("MatedMatrix::Evaluate"); gm = ((BaseMatrix*&)bm)->Evaluate(); GeneralMatrix* gmx = new Matrix; MatrixErrorNoSpace(gmx); gmx->nrows = nr; gmx->ncols = nc; gmx->storage = gm->storage; if (nr*nc != gmx->storage) Throw(IncompatibleDimensionsException()); #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmy = gm; delete this; return gmy->BorrowStore(gmx,mt); #else return gm->BorrowStore(gmx,mt); #endif } GeneralMatrix* GetSubMatrix::Evaluate(MatrixType mt) { REPORT Tracer tr("SubMatrix(evaluate)"); gm = ((BaseMatrix*&)bm)->Evaluate(); if (row_number < 0) row_number = gm->Nrows(); if (col_number < 0) col_number = gm->Ncols(); if (row_skip+row_number > gm->Nrows() || col_skip+col_number > gm->Ncols()) { gm->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif Throw(SubMatrixDimensionException()); } if (IsSym) Compare(gm->Type().ssub(), mt); else Compare(gm->Type().sub(), mt); GeneralMatrix* gmx = mt.New(row_number, col_number, this); int i = row_number; MatrixRow mr(gm, LoadOnEntry, row_skip); MatrixRow mrx(gmx, StoreOnExit+DirectPart); MatrixRowCol sub; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub mrx.Copy(sub); mrx.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } GeneralMatrix* ReturnMatrixX::Evaluate(MatrixType mt) { #ifdef TEMPS_DESTROYED_QUICKLY_R GeneralMatrix* gmx = gm; delete this; return gmx->Evaluate(mt); #else return gm->Evaluate(mt); #endif } void GeneralMatrix::Add(GeneralMatrix* gm1, Real f) { REPORT Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); while (i--) { *s++ = *s1++ + f; *s++ = *s1++ + f; *s++ = *s1++ + f; *s++ = *s1++ + f; } i = storage & 3; while (i--) *s++ = *s1++ + f; } void GeneralMatrix::Add(Real f) { REPORT Real* s=store; int i=(storage >> 2); while (i--) { *s++ += f; *s++ += f; *s++ += f; *s++ += f; } i = storage & 3; while (i--) *s++ += f; } void GeneralMatrix::NegAdd(GeneralMatrix* gm1, Real f) { REPORT Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); while (i--) { *s++ = f - *s1++; *s++ = f - *s1++; *s++ = f - *s1++; *s++ = f - *s1++; } i = storage & 3; while (i--) *s++ = f - *s1++; } void GeneralMatrix::NegAdd(Real f) { REPORT Real* s=store; int i=(storage >> 2); while (i--) { *s = f - *s; s++; *s = f - *s; s++; *s = f - *s; s++; *s = f - *s; s++; } i = storage & 3; while (i--) { *s = f - *s; s++; } } void GeneralMatrix::Negate(GeneralMatrix* gm1) { // change sign of elements REPORT Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); while (i--) { *s++ = -(*s1++); *s++ = -(*s1++); *s++ = -(*s1++); *s++ = -(*s1++); } i = storage & 3; while(i--) *s++ = -(*s1++); } void GeneralMatrix::Negate() { REPORT Real* s=store; int i=(storage >> 2); while (i--) { *s = -(*s); s++; *s = -(*s); s++; *s = -(*s); s++; *s = -(*s); s++; } i = storage & 3; while(i--) { *s = -(*s); s++; } } void GeneralMatrix::Multiply(GeneralMatrix* gm1, Real f) { REPORT Real* s1=gm1->store; Real* s=store; int i=(storage >> 2); while (i--) { *s++ = *s1++ * f; *s++ = *s1++ * f; *s++ = *s1++ * f; *s++ = *s1++ * f; } i = storage & 3; while (i--) *s++ = *s1++ * f; } void GeneralMatrix::Multiply(Real f) { REPORT Real* s=store; int i=(storage >> 2); while (i--) { *s++ *= f; *s++ *= f; *s++ *= f; *s++ *= f; } i = storage & 3; while (i--) *s++ *= f; } /************************ MatrixInput routines ****************************/ // int MatrixInput::n; // number values still to be read // Real* MatrixInput::r; // pointer to next location to be read to MatrixInput MatrixInput::operator<<(Real f) { REPORT Tracer et("MatrixInput"); if (n<=0) Throw(ProgramException("List of values too long")); *r = f; int n1 = n-1; n=0; // n=0 so we won't trigger exception return MatrixInput(n1, r+1); } MatrixInput GeneralMatrix::operator<<(Real f) { REPORT Tracer et("MatrixInput"); int n = Storage(); if (n<=0) Throw(ProgramException("Loading data to zero length matrix")); Real* r; r = Store(); *r = f; n--; return MatrixInput(n, r+1); } MatrixInput GetSubMatrix::operator<<(Real f) { REPORT Tracer et("MatrixInput (GetSubMatrix)"); SetUpLHS(); if (row_number != 1 || col_skip != 0 || col_number != gm->Ncols()) { #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif Throw(ProgramException("MatrixInput requires complete rows")); } MatrixRow mr(gm, DirectPart, row_skip); // to pick up location and length int n = mr.Storage(); if (n<=0) { #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif Throw(ProgramException("Loading data to zero length row")); } Real* r; r = mr.Data(); *r = f; n--; if (+(mr.cw*HaveStore)) { #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif Throw(ProgramException("Fails with this matrix type")); } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return MatrixInput(n, r+1); } MatrixInput::~MatrixInput() { REPORT Tracer et("MatrixInput"); if (n!=0) Throw(ProgramException("A list of values was too short")); } MatrixInput BandMatrix::operator<<(Real) { Tracer et("MatrixInput"); bool dummy = true; if (dummy) // get rid of warning message Throw(ProgramException("Cannot use list read with a BandMatrix")); return MatrixInput(0, 0); } void BandMatrix::operator<<(const Real*) { Throw(ProgramException("Cannot use array read with a BandMatrix")); } // ************************* Reverse order of elements *********************** void GeneralMatrix::ReverseElements(GeneralMatrix* gm) { // reversing into a new matrix REPORT int n = Storage(); Real* rx = Store() + n; Real* x = gm->Store(); while (n--) *(--rx) = *(x++); } void GeneralMatrix::ReverseElements() { // reversing in place REPORT int n = Storage(); Real* x = Store(); Real* rx = x + n; n /= 2; while (n--) { Real t = *(--rx); *rx = *x; *(x++) = t; } } #ifdef use_namespace } #endif newmat-1.10.4/newmat6.cpp0000644001161000116100000006473607415214514013404 0ustar rzrrzr//$$ newmat6.cpp Operators, element access, submatrices // Copyright (C) 1991,2,3,4: R B Davies #include "include.h" #include "newmat.h" #include "newmatrc.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,6); ++ExeCount; } #else #define REPORT {} #endif /*************************** general utilities *************************/ static int tristore(int n) // els in triangular matrix { return (n*(n+1))/2; } /****************************** operators *******************************/ Real& Matrix::operator()(int m, int n) { REPORT if (m<=0 || m>nrows || n<=0 || n>ncols) Throw(IndexException(m,n,*this)); return store[(m-1)*ncols+n-1]; } Real& SymmetricMatrix::operator()(int m, int n) { REPORT if (m<=0 || n<=0 || m>nrows || n>ncols) Throw(IndexException(m,n,*this)); if (m>=n) return store[tristore(m-1)+n-1]; else return store[tristore(n-1)+m-1]; } Real& UpperTriangularMatrix::operator()(int m, int n) { REPORT if (m<=0 || nncols) Throw(IndexException(m,n,*this)); return store[(m-1)*ncols+n-1-tristore(m-1)]; } Real& LowerTriangularMatrix::operator()(int m, int n) { REPORT if (n<=0 || mnrows) Throw(IndexException(m,n,*this)); return store[tristore(m-1)+n-1]; } Real& DiagonalMatrix::operator()(int m, int n) { REPORT if (n<=0 || m!=n || m>nrows || n>ncols) Throw(IndexException(m,n,*this)); return store[n-1]; } Real& DiagonalMatrix::operator()(int m) { REPORT if (m<=0 || m>nrows) Throw(IndexException(m,*this)); return store[m-1]; } Real& ColumnVector::operator()(int m) { REPORT if (m<=0 || m> nrows) Throw(IndexException(m,*this)); return store[m-1]; } Real& RowVector::operator()(int n) { REPORT if (n<=0 || n> ncols) Throw(IndexException(n,*this)); return store[n-1]; } Real& BandMatrix::operator()(int m, int n) { REPORT int w = upper+lower+1; int i = lower+n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real& UpperBandMatrix::operator()(int m, int n) { REPORT int w = upper+1; int i = n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real& LowerBandMatrix::operator()(int m, int n) { REPORT int w = lower+1; int i = lower+n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real& SymmetricBandMatrix::operator()(int m, int n) { REPORT int w = lower+1; if (m>=n) { REPORT int i = lower+n-m; if ( m>nrows || n<=0 || i<0 ) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } else { REPORT int i = lower+m-n; if ( n>nrows || m<=0 || i<0 ) Throw(IndexException(m,n,*this)); return store[w*(n-1)+i]; } } Real Matrix::operator()(int m, int n) const { REPORT if (m<=0 || m>nrows || n<=0 || n>ncols) Throw(IndexException(m,n,*this)); return store[(m-1)*ncols+n-1]; } Real SymmetricMatrix::operator()(int m, int n) const { REPORT if (m<=0 || n<=0 || m>nrows || n>ncols) Throw(IndexException(m,n,*this)); if (m>=n) return store[tristore(m-1)+n-1]; else return store[tristore(n-1)+m-1]; } Real UpperTriangularMatrix::operator()(int m, int n) const { REPORT if (m<=0 || nncols) Throw(IndexException(m,n,*this)); return store[(m-1)*ncols+n-1-tristore(m-1)]; } Real LowerTriangularMatrix::operator()(int m, int n) const { REPORT if (n<=0 || mnrows) Throw(IndexException(m,n,*this)); return store[tristore(m-1)+n-1]; } Real DiagonalMatrix::operator()(int m, int n) const { REPORT if (n<=0 || m!=n || m>nrows || n>ncols) Throw(IndexException(m,n,*this)); return store[n-1]; } Real DiagonalMatrix::operator()(int m) const { REPORT if (m<=0 || m>nrows) Throw(IndexException(m,*this)); return store[m-1]; } Real ColumnVector::operator()(int m) const { REPORT if (m<=0 || m> nrows) Throw(IndexException(m,*this)); return store[m-1]; } Real RowVector::operator()(int n) const { REPORT if (n<=0 || n> ncols) Throw(IndexException(n,*this)); return store[n-1]; } Real BandMatrix::operator()(int m, int n) const { REPORT int w = upper+lower+1; int i = lower+n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real UpperBandMatrix::operator()(int m, int n) const { REPORT int w = upper+1; int i = n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real LowerBandMatrix::operator()(int m, int n) const { REPORT int w = lower+1; int i = lower+n-m; if (m<=0 || m>nrows || n<=0 || n>ncols || i<0 || i>=w) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } Real SymmetricBandMatrix::operator()(int m, int n) const { REPORT int w = lower+1; if (m>=n) { REPORT int i = lower+n-m; if ( m>nrows || n<=0 || i<0 ) Throw(IndexException(m,n,*this)); return store[w*(m-1)+i]; } else { REPORT int i = lower+m-n; if ( n>nrows || m<=0 || i<0 ) Throw(IndexException(m,n,*this)); return store[w*(n-1)+i]; } } Real BaseMatrix::AsScalar() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); if (gm->nrows!=1 || gm->ncols!=1) { Tracer tr("AsScalar"); Try { Throw(ProgramException("Cannot convert to scalar", *gm)); } CatchAll { gm->tDelete(); ReThrow; } } Real x = *(gm->store); gm->tDelete(); return x; } #ifdef TEMPS_DESTROYED_QUICKLY AddedMatrix& BaseMatrix::operator+(const BaseMatrix& bm) const { REPORT AddedMatrix* x = new AddedMatrix(this, &bm); MatrixErrorNoSpace(x); return *x; } SPMatrix& SP(const BaseMatrix& bm1,const BaseMatrix& bm2) { REPORT SPMatrix* x = new SPMatrix(&bm1, &bm2); MatrixErrorNoSpace(x); return *x; } KPMatrix& KP(const BaseMatrix& bm1,const BaseMatrix& bm2) { REPORT KPMatrix* x = new KPMatrix(&bm1, &bm2); MatrixErrorNoSpace(x); return *x; } MultipliedMatrix& BaseMatrix::operator*(const BaseMatrix& bm) const { REPORT MultipliedMatrix* x = new MultipliedMatrix(this, &bm); MatrixErrorNoSpace(x); return *x; } ConcatenatedMatrix& BaseMatrix::operator|(const BaseMatrix& bm) const { REPORT ConcatenatedMatrix* x = new ConcatenatedMatrix(this, &bm); MatrixErrorNoSpace(x); return *x; } StackedMatrix& BaseMatrix::operator&(const BaseMatrix& bm) const { REPORT StackedMatrix* x = new StackedMatrix(this, &bm); MatrixErrorNoSpace(x); return *x; } //SolvedMatrix& InvertedMatrix::operator*(const BaseMatrix& bmx) const SolvedMatrix& InvertedMatrix::operator*(const BaseMatrix& bmx) { REPORT SolvedMatrix* x; Try { x = new SolvedMatrix(bm, &bmx); MatrixErrorNoSpace(x); } CatchAll { delete this; ReThrow; } delete this; // since we are using bm rather than this return *x; } SubtractedMatrix& BaseMatrix::operator-(const BaseMatrix& bm) const { REPORT SubtractedMatrix* x = new SubtractedMatrix(this, &bm); MatrixErrorNoSpace(x); return *x; } ShiftedMatrix& BaseMatrix::operator+(Real f) const { REPORT ShiftedMatrix* x = new ShiftedMatrix(this, f); MatrixErrorNoSpace(x); return *x; } NegShiftedMatrix& operator-(Real f,const BaseMatrix& bm1) { REPORT NegShiftedMatrix* x = new NegShiftedMatrix(f, &bm1); MatrixErrorNoSpace(x); return *x; } ScaledMatrix& BaseMatrix::operator*(Real f) const { REPORT ScaledMatrix* x = new ScaledMatrix(this, f); MatrixErrorNoSpace(x); return *x; } ScaledMatrix& BaseMatrix::operator/(Real f) const { REPORT ScaledMatrix* x = new ScaledMatrix(this, 1.0/f); MatrixErrorNoSpace(x); return *x; } ShiftedMatrix& BaseMatrix::operator-(Real f) const { REPORT ShiftedMatrix* x = new ShiftedMatrix(this, -f); MatrixErrorNoSpace(x); return *x; } TransposedMatrix& BaseMatrix::t() const { REPORT TransposedMatrix* x = new TransposedMatrix(this); MatrixErrorNoSpace(x); return *x; } NegatedMatrix& BaseMatrix::operator-() const { REPORT NegatedMatrix* x = new NegatedMatrix(this); MatrixErrorNoSpace(x); return *x; } ReversedMatrix& BaseMatrix::Reverse() const { REPORT ReversedMatrix* x = new ReversedMatrix(this); MatrixErrorNoSpace(x); return *x; } InvertedMatrix& BaseMatrix::i() const { REPORT InvertedMatrix* x = new InvertedMatrix(this); MatrixErrorNoSpace(x); return *x; } RowedMatrix& BaseMatrix::AsRow() const { REPORT RowedMatrix* x = new RowedMatrix(this); MatrixErrorNoSpace(x); return *x; } ColedMatrix& BaseMatrix::AsColumn() const { REPORT ColedMatrix* x = new ColedMatrix(this); MatrixErrorNoSpace(x); return *x; } DiagedMatrix& BaseMatrix::AsDiagonal() const { REPORT DiagedMatrix* x = new DiagedMatrix(this); MatrixErrorNoSpace(x); return *x; } MatedMatrix& BaseMatrix::AsMatrix(int nrx, int ncx) const { REPORT MatedMatrix* x = new MatedMatrix(this,nrx,ncx); MatrixErrorNoSpace(x); return *x; } #else AddedMatrix BaseMatrix::operator+(const BaseMatrix& bm) const { REPORT return AddedMatrix(this, &bm); } SPMatrix SP(const BaseMatrix& bm1,const BaseMatrix& bm2) { REPORT return SPMatrix(&bm1, &bm2); } KPMatrix KP(const BaseMatrix& bm1,const BaseMatrix& bm2) { REPORT return KPMatrix(&bm1, &bm2); } MultipliedMatrix BaseMatrix::operator*(const BaseMatrix& bm) const { REPORT return MultipliedMatrix(this, &bm); } ConcatenatedMatrix BaseMatrix::operator|(const BaseMatrix& bm) const { REPORT return ConcatenatedMatrix(this, &bm); } StackedMatrix BaseMatrix::operator&(const BaseMatrix& bm) const { REPORT return StackedMatrix(this, &bm); } SolvedMatrix InvertedMatrix::operator*(const BaseMatrix& bmx) const { REPORT return SolvedMatrix(bm, &bmx); } SubtractedMatrix BaseMatrix::operator-(const BaseMatrix& bm) const { REPORT return SubtractedMatrix(this, &bm); } ShiftedMatrix BaseMatrix::operator+(Real f) const { REPORT return ShiftedMatrix(this, f); } NegShiftedMatrix operator-(Real f, const BaseMatrix& bm) { REPORT return NegShiftedMatrix(f, &bm); } ScaledMatrix BaseMatrix::operator*(Real f) const { REPORT return ScaledMatrix(this, f); } ScaledMatrix BaseMatrix::operator/(Real f) const { REPORT return ScaledMatrix(this, 1.0/f); } ShiftedMatrix BaseMatrix::operator-(Real f) const { REPORT return ShiftedMatrix(this, -f); } TransposedMatrix BaseMatrix::t() const { REPORT return TransposedMatrix(this); } NegatedMatrix BaseMatrix::operator-() const { REPORT return NegatedMatrix(this); } ReversedMatrix BaseMatrix::Reverse() const { REPORT return ReversedMatrix(this); } InvertedMatrix BaseMatrix::i() const { REPORT return InvertedMatrix(this); } RowedMatrix BaseMatrix::AsRow() const { REPORT return RowedMatrix(this); } ColedMatrix BaseMatrix::AsColumn() const { REPORT return ColedMatrix(this); } DiagedMatrix BaseMatrix::AsDiagonal() const { REPORT return DiagedMatrix(this); } MatedMatrix BaseMatrix::AsMatrix(int nrx, int ncx) const { REPORT return MatedMatrix(this,nrx,ncx); } #endif void GeneralMatrix::operator=(Real f) { REPORT int i=storage; Real* s=store; while (i--) { *s++ = f; } } void Matrix::operator=(const BaseMatrix& X) { REPORT //CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::Rt); } void RowVector::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::RV); if (nrows!=1) { Tracer tr("RowVector(=)"); Throw(VectorException(*this)); } } void ColumnVector::operator=(const BaseMatrix& X) { REPORT //CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::CV); if (ncols!=1) { Tracer tr("ColumnVector(=)"); Throw(VectorException(*this)); } } void SymmetricMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::Sm); } void UpperTriangularMatrix::operator=(const BaseMatrix& X) { REPORT //CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::UT); } void LowerTriangularMatrix::operator=(const BaseMatrix& X) { REPORT //CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::LT); } void DiagonalMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::Dg); } void IdentityMatrix::operator=(const BaseMatrix& X) { REPORT // CheckConversion(X); // MatrixConversionCheck mcc; Eq(X,MatrixType::Id); } void GeneralMatrix::operator<<(const Real* r) { REPORT int i = storage; Real* s=store; while(i--) *s++ = *r++; } void GenericMatrix::operator=(const GenericMatrix& bmx) { if (&bmx != this) { REPORT if (gm) delete gm; gm = bmx.gm->Image();} else { REPORT } gm->Protect(); } void GenericMatrix::operator=(const BaseMatrix& bmx) { if (gm) { int counter=bmx.search(gm); if (counter==0) { REPORT delete gm; gm=0; } else { REPORT gm->Release(counter); } } else { REPORT } GeneralMatrix* gmx = ((BaseMatrix&)bmx).Evaluate(); if (gmx != gm) { REPORT if (gm) delete gm; gm = gmx->Image(); } else { REPORT } gm->Protect(); } /*************************** += etc ***************************************/ // will also need versions for SubMatrix // GeneralMatrix operators void GeneralMatrix::operator+=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator+="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY AddedMatrix* am = new AddedMatrix(this,gm); MatrixErrorNoSpace(am); if (gm==this) Release(2); else Release(); Eq2(*am,Type()); #else AddedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); #endif } void GeneralMatrix::operator-=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator-="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY SubtractedMatrix* am = new SubtractedMatrix(this,gm); MatrixErrorNoSpace(am); if (gm==this) Release(2); else Release(); Eq2(*am,Type()); #else SubtractedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); #endif } void GeneralMatrix::operator*=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator*="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY MultipliedMatrix* am = new MultipliedMatrix(this,gm); MatrixErrorNoSpace(am); if (gm==this) Release(2); else Release(); Eq2(*am,Type()); #else MultipliedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); #endif } void GeneralMatrix::operator|=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator|="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY ConcatenatedMatrix* am = new ConcatenatedMatrix(this,gm); MatrixErrorNoSpace(am); if (gm==this) Release(2); else Release(); Eq2(*am,Type()); #else ConcatenatedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); #endif } void GeneralMatrix::operator&=(const BaseMatrix& X) { REPORT Tracer tr("GeneralMatrix::operator&="); // MatrixConversionCheck mcc; Protect(); // so it cannot get deleted // during Evaluate GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY StackedMatrix* am = new StackedMatrix(this,gm); MatrixErrorNoSpace(am); if (gm==this) Release(2); else Release(); Eq2(*am,Type()); #else StackedMatrix am(this,gm); if (gm==this) Release(2); else Release(); Eq2(am,Type()); #endif } void GeneralMatrix::operator+=(Real r) { REPORT Tracer tr("GeneralMatrix::operator+=(Real)"); // MatrixConversionCheck mcc; #ifdef TEMPS_DESTROYED_QUICKLY ShiftedMatrix* am = new ShiftedMatrix(this,r); MatrixErrorNoSpace(am); Release(); Eq2(*am,Type()); #else ShiftedMatrix am(this,r); Release(); Eq2(am,Type()); #endif } void GeneralMatrix::operator*=(Real r) { REPORT Tracer tr("GeneralMatrix::operator*=(Real)"); // MatrixConversionCheck mcc; #ifdef TEMPS_DESTROYED_QUICKLY ScaledMatrix* am = new ScaledMatrix(this,r); MatrixErrorNoSpace(am); Release(); Eq2(*am,Type()); #else ScaledMatrix am(this,r); Release(); Eq2(am,Type()); #endif } // Generic matrix operators void GenericMatrix::operator+=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator+="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY AddedMatrix* am = new AddedMatrix(gm,gmx); MatrixErrorNoSpace(am); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am->Evaluate(); #else AddedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); #endif if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator-=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator-="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY SubtractedMatrix* am = new SubtractedMatrix(gm,gmx); MatrixErrorNoSpace(am); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am->Evaluate(); #else SubtractedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); #endif if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator*=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator*="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY MultipliedMatrix* am = new MultipliedMatrix(gm,gmx); MatrixErrorNoSpace(am); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am->Evaluate(); #else MultipliedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); #endif if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator|=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator|="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY ConcatenatedMatrix* am = new ConcatenatedMatrix(gm,gmx); MatrixErrorNoSpace(am); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am->Evaluate(); #else ConcatenatedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); #endif if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator&=(const BaseMatrix& X) { REPORT Tracer tr("GenericMatrix::operator&="); if (!gm) Throw(ProgramException("GenericMatrix is null")); gm->Protect(); // so it cannot get deleted during Evaluate GeneralMatrix* gmx = ((BaseMatrix&)X).Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY StackedMatrix* am = new StackedMatrix(gm,gmx); MatrixErrorNoSpace(am); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am->Evaluate(); #else StackedMatrix am(gm,gmx); if (gmx==gm) gm->Release(2); else gm->Release(); GeneralMatrix* gmy = am.Evaluate(); #endif if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator+=(Real r) { REPORT Tracer tr("GenericMatrix::operator+= (Real)"); if (!gm) Throw(ProgramException("GenericMatrix is null")); #ifdef TEMPS_DESTROYED_QUICKLY ShiftedMatrix* am = new ShiftedMatrix(gm,r); MatrixErrorNoSpace(am); gm->Release(); GeneralMatrix* gmy = am->Evaluate(); #else ShiftedMatrix am(gm,r); gm->Release(); GeneralMatrix* gmy = am.Evaluate(); #endif if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } void GenericMatrix::operator*=(Real r) { REPORT Tracer tr("GenericMatrix::operator*= (Real)"); if (!gm) Throw(ProgramException("GenericMatrix is null")); #ifdef TEMPS_DESTROYED_QUICKLY ScaledMatrix* am = new ScaledMatrix(gm,r); MatrixErrorNoSpace(am); gm->Release(); GeneralMatrix* gmy = am->Evaluate(); #else ScaledMatrix am(gm,r); gm->Release(); GeneralMatrix* gmy = am.Evaluate(); #endif if (gmy != gm) { REPORT delete gm; gm = gmy->Image(); } else { REPORT } gm->Protect(); } /************************* element access *********************************/ Real& Matrix::element(int m, int n) { REPORT if (m<0 || m>= nrows || n<0 || n>= ncols) Throw(IndexException(m,n,*this,true)); return store[m*ncols+n]; } Real Matrix::element(int m, int n) const { REPORT if (m<0 || m>= nrows || n<0 || n>= ncols) Throw(IndexException(m,n,*this,true)); return store[m*ncols+n]; } Real& SymmetricMatrix::element(int m, int n) { REPORT if (m<0 || n<0 || m >= nrows || n>=ncols) Throw(IndexException(m,n,*this,true)); if (m>=n) return store[tristore(m)+n]; else return store[tristore(n)+m]; } Real SymmetricMatrix::element(int m, int n) const { REPORT if (m<0 || n<0 || m >= nrows || n>=ncols) Throw(IndexException(m,n,*this,true)); if (m>=n) return store[tristore(m)+n]; else return store[tristore(n)+m]; } Real& UpperTriangularMatrix::element(int m, int n) { REPORT if (m<0 || n=ncols) Throw(IndexException(m,n,*this,true)); return store[m*ncols+n-tristore(m)]; } Real UpperTriangularMatrix::element(int m, int n) const { REPORT if (m<0 || n=ncols) Throw(IndexException(m,n,*this,true)); return store[m*ncols+n-tristore(m)]; } Real& LowerTriangularMatrix::element(int m, int n) { REPORT if (n<0 || m=nrows) Throw(IndexException(m,n,*this,true)); return store[tristore(m)+n]; } Real LowerTriangularMatrix::element(int m, int n) const { REPORT if (n<0 || m=nrows) Throw(IndexException(m,n,*this,true)); return store[tristore(m)+n]; } Real& DiagonalMatrix::element(int m, int n) { REPORT if (n<0 || m!=n || m>=nrows || n>=ncols) Throw(IndexException(m,n,*this,true)); return store[n]; } Real DiagonalMatrix::element(int m, int n) const { REPORT if (n<0 || m!=n || m>=nrows || n>=ncols) Throw(IndexException(m,n,*this,true)); return store[n]; } Real& DiagonalMatrix::element(int m) { REPORT if (m<0 || m>=nrows) Throw(IndexException(m,*this,true)); return store[m]; } Real DiagonalMatrix::element(int m) const { REPORT if (m<0 || m>=nrows) Throw(IndexException(m,*this,true)); return store[m]; } Real& ColumnVector::element(int m) { REPORT if (m<0 || m>= nrows) Throw(IndexException(m,*this,true)); return store[m]; } Real ColumnVector::element(int m) const { REPORT if (m<0 || m>= nrows) Throw(IndexException(m,*this,true)); return store[m]; } Real& RowVector::element(int n) { REPORT if (n<0 || n>= ncols) Throw(IndexException(n,*this,true)); return store[n]; } Real RowVector::element(int n) const { REPORT if (n<0 || n>= ncols) Throw(IndexException(n,*this,true)); return store[n]; } Real& BandMatrix::element(int m, int n) { REPORT int w = upper+lower+1; int i = lower+n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real BandMatrix::element(int m, int n) const { REPORT int w = upper+lower+1; int i = lower+n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real& UpperBandMatrix::element(int m, int n) { REPORT int w = upper+1; int i = n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real UpperBandMatrix::element(int m, int n) const { REPORT int w = upper+1; int i = n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real& LowerBandMatrix::element(int m, int n) { REPORT int w = lower+1; int i = lower+n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real LowerBandMatrix::element(int m, int n) const { REPORT int w = lower+1; int i = lower+n-m; if (m<0 || m>= nrows || n<0 || n>= ncols || i<0 || i>=w) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } Real& SymmetricBandMatrix::element(int m, int n) { REPORT int w = lower+1; if (m>=n) { REPORT int i = lower+n-m; if ( m>=nrows || n<0 || i<0 ) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } else { REPORT int i = lower+m-n; if ( n>=nrows || m<0 || i<0 ) Throw(IndexException(m,n,*this,true)); return store[w*n+i]; } } Real SymmetricBandMatrix::element(int m, int n) const { REPORT int w = lower+1; if (m>=n) { REPORT int i = lower+n-m; if ( m>=nrows || n<0 || i<0 ) Throw(IndexException(m,n,*this,true)); return store[w*m+i]; } else { REPORT int i = lower+m-n; if ( n>=nrows || m<0 || i<0 ) Throw(IndexException(m,n,*this,true)); return store[w*n+i]; } } #ifdef use_namespace } #endif newmat-1.10.4/newmat7.cpp0000644001161000116100000007600407415172310013371 0ustar rzrrzr//$$ newmat7.cpp Invert, solve, binary operations // Copyright (C) 1991,2,3,4: R B Davies #include "include.h" #include "newmat.h" #include "newmatrc.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,7); ++ExeCount; } #else #define REPORT {} #endif //***************************** solve routines ******************************/ GeneralMatrix* GeneralMatrix::MakeSolver() { REPORT GeneralMatrix* gm = new CroutMatrix(*this); MatrixErrorNoSpace(gm); gm->ReleaseAndDelete(); return gm; } GeneralMatrix* Matrix::MakeSolver() { REPORT GeneralMatrix* gm = new CroutMatrix(*this); MatrixErrorNoSpace(gm); gm->ReleaseAndDelete(); return gm; } void CroutMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip; Real* el = mcin.data-i; Real* el1 = el; while (i--) *el++ = 0.0; el += mcin.storage; i = nrows - mcin.skip - mcin.storage; while (i--) *el++ = 0.0; lubksb(el1, mcout.skip); } // Do we need check for entirely zero output? void UpperTriangularMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip-mcout.skip; Real* elx = mcin.data-i; while (i-- > 0) *elx++ = 0.0; int nr = mcin.skip+mcin.storage; elx = mcin.data+mcin.storage; Real* el = elx; int j = mcout.skip+mcout.storage-nr; int nc = ncols-nr; i = nr-mcout.skip; while (j-- > 0) *elx++ = 0.0; Real* Ael = store + (nr*(2*ncols-nr+1))/2; j = 0; while (i-- > 0) { elx = el; Real sum = 0.0; int jx = j++; Ael -= nc; while (jx--) sum += *(--Ael) * *(--elx); elx--; *elx = (*elx - sum) / *(--Ael); } } void LowerTriangularMatrix::Solver(MatrixColX& mcout, const MatrixColX& mcin) { REPORT int i = mcin.skip-mcout.skip; Real* elx = mcin.data-i; while (i-- > 0) *elx++ = 0.0; int nc = mcin.skip; i = nc+mcin.storage; elx = mcin.data+mcin.storage; int nr = mcout.skip+mcout.storage; int j = nr-i; i = nr-nc; while (j-- > 0) *elx++ = 0.0; Real* el = mcin.data; Real* Ael = store + (nc*(nc+1))/2; j = 0; while (i-- > 0) { elx = el; Real sum = 0.0; int jx = j++; Ael += nc; while (jx--) sum += *Ael++ * *elx++; *elx = (*elx - sum) / *Ael++; } } //******************* carry out binary operations *************************/ static GeneralMatrix* GeneralMult(GeneralMatrix*,GeneralMatrix*,MultipliedMatrix*,MatrixType); static GeneralMatrix* GeneralSolv(GeneralMatrix*,GeneralMatrix*,BaseMatrix*,MatrixType); static GeneralMatrix* GeneralSolvI(GeneralMatrix*,BaseMatrix*,MatrixType); static GeneralMatrix* GeneralKP(GeneralMatrix*,GeneralMatrix*,KPMatrix*,MatrixType); GeneralMatrix* MultipliedMatrix::Evaluate(MatrixType mt) { REPORT gm2 = ((BaseMatrix*&)bm2)->Evaluate(); gm2 = gm2->Evaluate(gm2->Type().MultRHS()); // no symmetric on RHS gm1=((BaseMatrix*&)bm1)->Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmx; Try { gmx = GeneralMult(gm1, gm2, this, mt); } CatchAll { delete this; ReThrow; } delete this; return gmx; #else return GeneralMult(gm1, gm2, this, mt); #endif } GeneralMatrix* SolvedMatrix::Evaluate(MatrixType mt) { REPORT gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmx; Try { gmx = GeneralSolv(gm1,gm2,this,mt); } CatchAll { delete this; ReThrow; } delete this; return gmx; #else return GeneralSolv(gm1,gm2,this,mt); #endif } GeneralMatrix* KPMatrix::Evaluate(MatrixType mt) { REPORT gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmx; Try { gmx = GeneralKP(gm1,gm2,this,mt); } CatchAll { delete this; ReThrow; } delete this; return gmx; #else return GeneralKP(gm1,gm2,this,mt); #endif } // routines for adding or subtracting matrices of identical storage structure static void Add(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT Real* s1=gm1->Store(); Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ = *s1++ + *s2++; *s++ = *s1++ + *s2++; *s++ = *s1++ + *s2++; *s++ = *s1++ + *s2++; } i=gm->Storage() & 3; while (i--) *s++ = *s1++ + *s2++; } static void Add(GeneralMatrix* gm, GeneralMatrix* gm2) { REPORT Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ += *s2++; *s++ += *s2++; *s++ += *s2++; *s++ += *s2++; } i=gm->Storage() & 3; while (i--) *s++ += *s2++; } static void Subtract(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT Real* s1=gm1->Store(); Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ = *s1++ - *s2++; *s++ = *s1++ - *s2++; *s++ = *s1++ - *s2++; *s++ = *s1++ - *s2++; } i=gm->Storage() & 3; while (i--) *s++ = *s1++ - *s2++; } static void Subtract(GeneralMatrix* gm, GeneralMatrix* gm2) { REPORT Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ -= *s2++; *s++ -= *s2++; *s++ -= *s2++; *s++ -= *s2++; } i=gm->Storage() & 3; while (i--) *s++ -= *s2++; } static void ReverseSubtract(GeneralMatrix* gm, GeneralMatrix* gm2) { REPORT Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s = *s2++ - *s; s++; *s = *s2++ - *s; s++; *s = *s2++ - *s; s++; *s = *s2++ - *s; s++; } i=gm->Storage() & 3; while (i--) { *s = *s2++ - *s; s++; } } static void SP(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT Real* s1=gm1->Store(); Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ = *s1++ * *s2++; *s++ = *s1++ * *s2++; *s++ = *s1++ * *s2++; *s++ = *s1++ * *s2++; } i=gm->Storage() & 3; while (i--) *s++ = *s1++ * *s2++; } static void SP(GeneralMatrix* gm, GeneralMatrix* gm2) { REPORT Real* s2=gm2->Store(); Real* s=gm->Store(); int i=gm->Storage() >> 2; while (i--) { *s++ *= *s2++; *s++ *= *s2++; *s++ *= *s2++; *s++ *= *s2++; } i=gm->Storage() & 3; while (i--) *s++ *= *s2++; } // routines for adding or subtracting matrices of different storage structure static void AddDS(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gm, StoreOnExit+DirectPart); while (nr--) { mr.Add(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } } static void AddDS(GeneralMatrix* gm, GeneralMatrix* gm2) // Add into first argument { REPORT int nr = gm->Nrows(); MatrixRow mr(gm, StoreOnExit+LoadOnEntry+DirectPart); MatrixRow mr2(gm2, LoadOnEntry); while (nr--) { mr.Add(mr2); mr.Next(); mr2.Next(); } } static void SubtractDS (GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gm, StoreOnExit+DirectPart); while (nr--) { mr.Sub(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } } static void SubtractDS(GeneralMatrix* gm, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart); MatrixRow mr2(gm2, LoadOnEntry); while (nr--) { mr.Sub(mr2); mr.Next(); mr2.Next(); } } static void ReverseSubtractDS(GeneralMatrix* gm, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart); MatrixRow mr2(gm2, LoadOnEntry); while (nr--) { mr.RevSub(mr2); mr2.Next(); mr.Next(); } } static void SPDS(GeneralMatrix* gm, GeneralMatrix* gm1, GeneralMatrix* gm2) { REPORT int nr = gm->Nrows(); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gm, StoreOnExit+DirectPart); while (nr--) { mr.Multiply(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } } static void SPDS(GeneralMatrix* gm, GeneralMatrix* gm2) // SP into first argument { REPORT int nr = gm->Nrows(); MatrixRow mr(gm, StoreOnExit+LoadOnEntry+DirectPart); MatrixRow mr2(gm2, LoadOnEntry); while (nr--) { mr.Multiply(mr2); mr.Next(); mr2.Next(); } } static GeneralMatrix* GeneralMult1(GeneralMatrix* gm1, GeneralMatrix* gm2, MultipliedMatrix* mm, MatrixType mtx) { REPORT Tracer tr("GeneralMult1"); int nr=gm1->Nrows(); int nc=gm2->Ncols(); if (gm1->Ncols() !=gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr,nc,mm); MatrixCol mcx(gmx, StoreOnExit+DirectPart); MatrixCol mc2(gm2, LoadOnEntry); while (nc--) { MatrixRow mr1(gm1, LoadOnEntry, mcx.Skip()); Real* el = mcx.Data(); // pointer to an element int n = mcx.Storage(); while (n--) { *(el++) = DotProd(mr1,mc2); mr1.Next(); } mc2.Next(); mcx.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; } static GeneralMatrix* GeneralMult2(GeneralMatrix* gm1, GeneralMatrix* gm2, MultipliedMatrix* mm, MatrixType mtx) { // version that accesses by row only - not good for thin matrices // or column vectors in right hand term. REPORT Tracer tr("GeneralMult2"); int nr=gm1->Nrows(); int nc=gm2->Ncols(); if (gm1->Ncols() !=gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr,nc,mm); MatrixRow mrx(gmx, LoadOnEntry+StoreOnExit+DirectPart); MatrixRow mr1(gm1, LoadOnEntry); while (nr--) { MatrixRow mr2(gm2, LoadOnEntry, mr1.Skip()); Real* el = mr1.Data(); // pointer to an element int n = mr1.Storage(); mrx.Zero(); while (n--) { mrx.AddScaled(mr2, *el++); mr2.Next(); } mr1.Next(); mrx.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; } static GeneralMatrix* mmMult(GeneralMatrix* gm1, GeneralMatrix* gm2) { // matrix multiplication for type Matrix only REPORT Tracer tr("MatrixMult"); int nr=gm1->Nrows(); int ncr=gm1->Ncols(); int nc=gm2->Ncols(); if (ncr != gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1,*gm2)); Matrix* gm = new Matrix(nr,nc); MatrixErrorNoSpace(gm); Real* s1=gm1->Store(); Real* s2=gm2->Store(); Real* s=gm->Store(); if (ncr) { while (nr--) { Real* s2x = s2; int j = ncr; Real* sx = s; Real f = *s1++; int k = nc; while (k--) *sx++ = f * *s2x++; while (--j) { sx = s; f = *s1++; k = nc; while (k--) *sx++ += f * *s2x++; } s = sx; } } else *gm = 0.0; gm->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gm; } static GeneralMatrix* GeneralMult(GeneralMatrix* gm1, GeneralMatrix* gm2, MultipliedMatrix* mm, MatrixType mtx) { if ( Rectangular(gm1->Type(), gm2->Type(), mtx)) { REPORT return mmMult(gm1, gm2); } else { REPORT Compare(gm1->Type() * gm2->Type(),mtx); int nr = gm2->Nrows(); int nc = gm2->Ncols(); if (nc <= 5 && nr > nc) { REPORT return GeneralMult1(gm1, gm2, mm, mtx); } else { REPORT return GeneralMult2(gm1, gm2, mm, mtx); } } } static GeneralMatrix* GeneralKP(GeneralMatrix* gm1, GeneralMatrix* gm2, KPMatrix* kp, MatrixType mtx) { REPORT Tracer tr("GeneralKP"); int nr1 = gm1->Nrows(); int nc1 = gm1->Ncols(); int nr2 = gm2->Nrows(); int nc2 = gm2->Ncols(); Compare((gm1->Type()).KP(gm2->Type()),mtx); GeneralMatrix* gmx = mtx.New(nr1*nr2, nc1*nc2, kp); MatrixRow mrx(gmx, LoadOnEntry+StoreOnExit+DirectPart); MatrixRow mr1(gm1, LoadOnEntry); for (int i = 1; i <= nr1; ++i) { MatrixRow mr2(gm2, LoadOnEntry); for (int j = 1; j <= nr2; ++j) { mrx.KP(mr1,mr2); mr2.Next(); mrx.Next(); } mr1.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; } static GeneralMatrix* GeneralSolv(GeneralMatrix* gm1, GeneralMatrix* gm2, BaseMatrix* sm, MatrixType mtx) { REPORT Tracer tr("GeneralSolv"); Compare(gm1->Type().i() * gm2->Type(),mtx); int nr = gm1->Nrows(); if (nr != gm1->Ncols()) Throw(NotSquareException(*gm1)); int nc = gm2->Ncols(); if (gm1->Ncols() != gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr,nc,sm); MatrixErrorNoSpace(gmx); Real* r = new Real [nr]; MatrixErrorNoSpace(r); MONITOR_REAL_NEW("Make (GenSolv)",nr,r) GeneralMatrix* gms = gm1->MakeSolver(); Try { MatrixColX mcx(gmx, r, StoreOnExit+DirectPart); // copy to and from r // this must be inside Try so mcx is destroyed before gmx MatrixColX mc2(gm2, r, LoadOnEntry); while (nc--) { gms->Solver(mcx, mc2); mcx.Next(); mc2.Next(); } } CatchAll { if (gms) gms->tDelete(); delete gmx; // <-------------------- gm2->tDelete(); MONITOR_REAL_DELETE("Delete (GenSolv)",nr,r) // ATandT version 2.1 gives an internal error delete [] r; ReThrow; } gms->tDelete(); gmx->ReleaseAndDelete(); gm2->tDelete(); MONITOR_REAL_DELETE("Delete (GenSolv)",nr,r) // ATandT version 2.1 gives an internal error delete [] r; return gmx; } // version for inverses - gm2 is identity static GeneralMatrix* GeneralSolvI(GeneralMatrix* gm1, BaseMatrix* sm, MatrixType mtx) { REPORT Tracer tr("GeneralSolvI"); Compare(gm1->Type().i(),mtx); int nr = gm1->Nrows(); if (nr != gm1->Ncols()) Throw(NotSquareException(*gm1)); int nc = nr; // DiagonalMatrix I(nr); I = 1; IdentityMatrix I(nr); GeneralMatrix* gmx = mtx.New(nr,nc,sm); MatrixErrorNoSpace(gmx); Real* r = new Real [nr]; MatrixErrorNoSpace(r); MONITOR_REAL_NEW("Make (GenSolvI)",nr,r) GeneralMatrix* gms = gm1->MakeSolver(); Try { MatrixColX mcx(gmx, r, StoreOnExit+DirectPart); // copy to and from r // this must be inside Try so mcx is destroyed before gmx MatrixColX mc2(&I, r, LoadOnEntry); while (nc--) { gms->Solver(mcx, mc2); mcx.Next(); mc2.Next(); } } CatchAll { if (gms) gms->tDelete(); delete gmx; MONITOR_REAL_DELETE("Delete (GenSolvI)",nr,r) // ATandT version 2.1 gives an internal error delete [] r; ReThrow; } gms->tDelete(); gmx->ReleaseAndDelete(); MONITOR_REAL_DELETE("Delete (GenSolvI)",nr,r) // ATandT version 2.1 gives an internal error delete [] r; return gmx; } GeneralMatrix* InvertedMatrix::Evaluate(MatrixType mtx) { // Matrix Inversion - use solve routines Tracer tr("InvertedMatrix::Evaluate"); REPORT gm=((BaseMatrix*&)bm)->Evaluate(); #ifdef TEMPS_DESTROYED_QUICKLY GeneralMatrix* gmx; Try { gmx = GeneralSolvI(gm,this,mtx); } CatchAll { delete this; ReThrow; } delete this; return gmx; #else return GeneralSolvI(gm,this,mtx); #endif } //*************************** New versions ************************ GeneralMatrix* AddedMatrix::Evaluate(MatrixType mtd) { REPORT Tracer tr("AddedMatrix::Evaluate"); gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); int nr=gm1->Nrows(); int nc=gm1->Ncols(); if (nr!=gm2->Nrows() || nc!=gm2->Ncols()) { Try { Throw(IncompatibleDimensionsException(*gm1, *gm2)); } CatchAll { gm1->tDelete(); gm2->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } } MatrixType mt1 = gm1->Type(), mt2 = gm2->Type(); MatrixType mts = mt1 + mt2; if (!mtd) { REPORT mtd = mts; } else if (!(mtd.DataLossOK || mtd >= mts)) { REPORT gm1->tDelete(); gm2->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif Throw(ProgramException("Illegal Conversion", mts, mtd)); } GeneralMatrix* gmx; bool c1 = (mtd == mt1), c2 = (mtd == mt2); if ( c1 && c2 && (gm1->SimpleAddOK(gm2) == 0) ) { if (gm1->reuse()) { REPORT Add(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (gm2->reuse()) { REPORT Add(gm2,gm1); gmx = gm2; } else { REPORT // what if new throws an exception Try { gmx = mt1.New(nr,nc,this); } CatchAll { #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } gmx->ReleaseAndDelete(); Add(gmx,gm1,gm2); } } else { if (c1 && c2) { short SAO = gm1->SimpleAddOK(gm2); if (SAO & 1) { REPORT c1 = false; } if (SAO & 2) { REPORT c2 = false; } } if (c1 && gm1->reuse() ) // must have type test first { REPORT AddDS(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (c2 && gm2->reuse() ) { REPORT AddDS(gm2,gm1); if (!c1) gm1->tDelete(); gmx = gm2; } else { REPORT Try { gmx = mtd.New(nr,nc,this); } CatchAll { if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } AddDS(gmx,gm1,gm2); if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); gmx->ReleaseAndDelete(); } } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } GeneralMatrix* SubtractedMatrix::Evaluate(MatrixType mtd) { REPORT Tracer tr("SubtractedMatrix::Evaluate"); gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); int nr=gm1->Nrows(); int nc=gm1->Ncols(); if (nr!=gm2->Nrows() || nc!=gm2->Ncols()) { Try { Throw(IncompatibleDimensionsException(*gm1, *gm2)); } CatchAll { gm1->tDelete(); gm2->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } } MatrixType mt1 = gm1->Type(), mt2 = gm2->Type(); MatrixType mts = mt1 + mt2; if (!mtd) { REPORT mtd = mts; } else if (!(mtd.DataLossOK || mtd >= mts)) { gm1->tDelete(); gm2->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif Throw(ProgramException("Illegal Conversion", mts, mtd)); } GeneralMatrix* gmx; bool c1 = (mtd == mt1), c2 = (mtd == mt2); if ( c1 && c2 && (gm1->SimpleAddOK(gm2) == 0) ) { if (gm1->reuse()) { REPORT Subtract(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (gm2->reuse()) { REPORT ReverseSubtract(gm2,gm1); gmx = gm2; } else { REPORT Try { gmx = mt1.New(nr,nc,this); } CatchAll { #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } gmx->ReleaseAndDelete(); Subtract(gmx,gm1,gm2); } } else { if (c1 && c2) { short SAO = gm1->SimpleAddOK(gm2); if (SAO & 1) { REPORT c1 = false; } if (SAO & 2) { REPORT c2 = false; } } if (c1 && gm1->reuse() ) // must have type test first { REPORT SubtractDS(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (c2 && gm2->reuse() ) { REPORT ReverseSubtractDS(gm2,gm1); if (!c1) gm1->tDelete(); gmx = gm2; } else { REPORT // what if New throws and exception Try { gmx = mtd.New(nr,nc,this); } CatchAll { if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } SubtractDS(gmx,gm1,gm2); if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); gmx->ReleaseAndDelete(); } } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } GeneralMatrix* SPMatrix::Evaluate(MatrixType mtd) { REPORT Tracer tr("SPMatrix::Evaluate"); gm1=((BaseMatrix*&)bm1)->Evaluate(); gm2=((BaseMatrix*&)bm2)->Evaluate(); int nr=gm1->Nrows(); int nc=gm1->Ncols(); if (nr!=gm2->Nrows() || nc!=gm2->Ncols()) { Try { Throw(IncompatibleDimensionsException(*gm1, *gm2)); } CatchAll { gm1->tDelete(); gm2->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } } MatrixType mt1 = gm1->Type(), mt2 = gm2->Type(); MatrixType mts = mt1.SP(mt2); if (!mtd) { REPORT mtd = mts; } else if (!(mtd.DataLossOK || mtd >= mts)) { gm1->tDelete(); gm2->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif Throw(ProgramException("Illegal Conversion", mts, mtd)); } GeneralMatrix* gmx; bool c1 = (mtd == mt1), c2 = (mtd == mt2); if ( c1 && c2 && (gm1->SimpleAddOK(gm2) == 0) ) { if (gm1->reuse()) { REPORT SP(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (gm2->reuse()) { REPORT SP(gm2,gm1); gmx = gm2; } else { REPORT Try { gmx = mt1.New(nr,nc,this); } CatchAll { #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } gmx->ReleaseAndDelete(); SP(gmx,gm1,gm2); } } else { if (c1 && c2) { short SAO = gm1->SimpleAddOK(gm2); if (SAO & 1) { REPORT c2 = false; } // c1 and c2 swapped if (SAO & 2) { REPORT c1 = false; } } if (c1 && gm1->reuse() ) // must have type test first { REPORT SPDS(gm1,gm2); gm2->tDelete(); gmx = gm1; } else if (c2 && gm2->reuse() ) { REPORT SPDS(gm2,gm1); if (!c1) gm1->tDelete(); gmx = gm2; } else { REPORT // what if New throws and exception Try { gmx = mtd.New(nr,nc,this); } CatchAll { if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } SPDS(gmx,gm1,gm2); if (!c1) gm1->tDelete(); if (!c2) gm2->tDelete(); gmx->ReleaseAndDelete(); } } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif return gmx; } //*************************** norm functions ****************************/ Real BaseMatrix::Norm1() const { // maximum of sum of absolute values of a column REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); int nc = gm->Ncols(); Real value = 0.0; MatrixCol mc(gm, LoadOnEntry); while (nc--) { Real v = mc.SumAbsoluteValue(); if (value < v) value = v; mc.Next(); } gm->tDelete(); return value; } Real BaseMatrix::NormInfinity() const { // maximum of sum of absolute values of a row REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); int nr = gm->Nrows(); Real value = 0.0; MatrixRow mr(gm, LoadOnEntry); while (nr--) { Real v = mr.SumAbsoluteValue(); if (value < v) value = v; mr.Next(); } gm->tDelete(); return value; } //********************** Concatenation and stacking *************************/ GeneralMatrix* ConcatenatedMatrix::Evaluate(MatrixType mtx) { REPORT Tracer tr("Concatenate"); #ifdef TEMPS_DESTROYED_QUICKLY Try { gm2 = ((BaseMatrix*&)bm2)->Evaluate(); gm1 = ((BaseMatrix*&)bm1)->Evaluate(); Compare(gm1->Type() | gm2->Type(),mtx); int nr=gm1->Nrows(); int nc = gm1->Ncols() + gm2->Ncols(); if (nr != gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr,nc,this); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gmx, StoreOnExit+DirectPart); while (nr--) { mr.ConCat(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); delete this; return gmx; } CatchAll { delete this; ReThrow; } #ifndef UseExceptions return 0; #endif #else gm2 = ((BaseMatrix*&)bm2)->Evaluate(); gm1 = ((BaseMatrix*&)bm1)->Evaluate(); Compare(gm1->Type() | gm2->Type(),mtx); int nr=gm1->Nrows(); int nc = gm1->Ncols() + gm2->Ncols(); if (nr != gm2->Nrows()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr,nc,this); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gmx, StoreOnExit+DirectPart); while (nr--) { mr.ConCat(mr1,mr2); mr1.Next(); mr2.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; #endif } GeneralMatrix* StackedMatrix::Evaluate(MatrixType mtx) { REPORT Tracer tr("Stack"); #ifdef TEMPS_DESTROYED_QUICKLY Try { gm2 = ((BaseMatrix*&)bm2)->Evaluate(); gm1 = ((BaseMatrix*&)bm1)->Evaluate(); Compare(gm1->Type() & gm2->Type(),mtx); int nc=gm1->Ncols(); int nr1 = gm1->Nrows(); int nr2 = gm2->Nrows(); if (nc != gm2->Ncols()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr1+nr2,nc,this); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gmx, StoreOnExit+DirectPart); while (nr1--) { mr.Copy(mr1); mr1.Next(); mr.Next(); } while (nr2--) { mr.Copy(mr2); mr2.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); delete this; return gmx; } CatchAll { delete this; ReThrow; } #ifndef UseExceptions return 0; #endif #else gm2 = ((BaseMatrix*&)bm2)->Evaluate(); gm1 = ((BaseMatrix*&)bm1)->Evaluate(); Compare(gm1->Type() & gm2->Type(),mtx); int nc=gm1->Ncols(); int nr1 = gm1->Nrows(); int nr2 = gm2->Nrows(); if (nc != gm2->Ncols()) Throw(IncompatibleDimensionsException(*gm1, *gm2)); GeneralMatrix* gmx = mtx.New(nr1+nr2,nc,this); MatrixRow mr1(gm1, LoadOnEntry); MatrixRow mr2(gm2, LoadOnEntry); MatrixRow mr(gmx, StoreOnExit+DirectPart); while (nr1--) { mr.Copy(mr1); mr1.Next(); mr.Next(); } while (nr2--) { mr.Copy(mr2); mr2.Next(); mr.Next(); } gmx->ReleaseAndDelete(); gm1->tDelete(); gm2->tDelete(); return gmx; #endif } // ************************* equality of matrices ******************** // static bool RealEqual(Real* s1, Real* s2, int n) { int i = n >> 2; while (i--) { if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; } i = n & 3; while (i--) if (*s1++ != *s2++) return false; return true; } static bool intEqual(int* s1, int* s2, int n) { int i = n >> 2; while (i--) { if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; if (*s1++ != *s2++) return false; } i = n & 3; while (i--) if (*s1++ != *s2++) return false; return true; } bool operator==(const BaseMatrix& A, const BaseMatrix& B) { Tracer tr("BaseMatrix =="); REPORT GeneralMatrix* gmA = ((BaseMatrix&)A).Evaluate(); GeneralMatrix* gmB = ((BaseMatrix&)B).Evaluate(); if (gmA == gmB) // same matrix { REPORT gmA->tDelete(); return true; } if ( gmA->Nrows() != gmB->Nrows() || gmA->Ncols() != gmB->Ncols() ) // different dimensions { REPORT gmA->tDelete(); gmB->tDelete(); return false; } // check for CroutMatrix or BandLUMatrix MatrixType AType = gmA->Type(); MatrixType BType = gmB->Type(); if (AType.CannotConvert() || BType.CannotConvert() ) { REPORT bool bx = gmA->IsEqual(*gmB); gmA->tDelete(); gmB->tDelete(); return bx; } // is matrix storage the same // will need to modify if further matrix structures are introduced if (AType == BType && gmA->BandWidth() == gmB->BandWidth()) { // compare store REPORT bool bx = RealEqual(gmA->Store(),gmB->Store(),gmA->Storage()); gmA->tDelete(); gmB->tDelete(); return bx; } // matrix storage different - just subtract REPORT return IsZero(*gmA-*gmB); } bool operator==(const GeneralMatrix& A, const GeneralMatrix& B) { Tracer tr("GeneralMatrix =="); // May or may not call tDeletes REPORT if (&A == &B) // same matrix { REPORT return true; } if ( A.Nrows() != B.Nrows() || A.Ncols() != B.Ncols() ) { REPORT return false; } // different dimensions // check for CroutMatrix or BandLUMatrix MatrixType AType = A.Type(); MatrixType BType = B.Type(); if (AType.CannotConvert() || BType.CannotConvert() ) { REPORT return A.IsEqual(B); } // is matrix storage the same // will need to modify if further matrix structures are introduced if (AType == BType && A.BandWidth() == B.BandWidth()) { REPORT return RealEqual(A.Store(),B.Store(),A.Storage()); } // matrix storage different - just subtract REPORT return IsZero(A-B); } bool GeneralMatrix::IsZero() const { REPORT Real* s=store; int i = storage >> 2; while (i--) { if (*s++) return false; if (*s++) return false; if (*s++) return false; if (*s++) return false; } i = storage & 3; while (i--) if (*s++) return false; return true; } bool IsZero(const BaseMatrix& A) { Tracer tr("BaseMatrix::IsZero"); REPORT GeneralMatrix* gm1 = 0; bool bx; Try { gm1=((BaseMatrix&)A).Evaluate(); bx = gm1->IsZero(); } CatchAll { if (gm1) gm1->tDelete(); ReThrow; } gm1->tDelete(); return bx; } // IsEqual functions - insist matrices are of same type // as well as equal values to be equal bool GeneralMatrix::IsEqual(const GeneralMatrix& A) const { Tracer tr("GeneralMatrix IsEqual"); if (A.Type() != Type()) // not same types { REPORT return false; } if (&A == this) // same matrix { REPORT return true; } if (A.nrows != nrows || A.ncols != ncols) // different dimensions { REPORT return false; } // is matrix storage the same - compare store REPORT return RealEqual(A.store,store,storage); } bool CroutMatrix::IsEqual(const GeneralMatrix& A) const { Tracer tr("CroutMatrix IsEqual"); if (A.Type() != Type()) // not same types { REPORT return false; } if (&A == this) // same matrix { REPORT return true; } if (A.nrows != nrows || A.ncols != ncols) // different dimensions { REPORT return false; } // is matrix storage the same - compare store REPORT return RealEqual(A.store,store,storage) && intEqual(((CroutMatrix&)A).indx, indx, nrows); } bool BandLUMatrix::IsEqual(const GeneralMatrix& A) const { Tracer tr("BandLUMatrix IsEqual"); if (A.Type() != Type()) // not same types { REPORT return false; } if (&A == this) // same matrix { REPORT return true; } if ( A.Nrows() != nrows || A.Ncols() != ncols || ((BandLUMatrix&)A).m1 != m1 || ((BandLUMatrix&)A).m2 != m2 ) // different dimensions { REPORT return false; } // matrix storage the same - compare store REPORT return RealEqual(A.Store(),store,storage) && RealEqual(((BandLUMatrix&)A).store2,store2,storage2) && intEqual(((BandLUMatrix&)A).indx, indx, nrows); } #ifdef use_namespace } #endif newmat-1.10.4/newmat8.cpp0000644001161000116100000004661010404727374013402 0ustar rzrrzr//$$ newmat8.cpp Advanced LU transform, scalar functions // Copyright (C) 1991,2,3,4,8: R B Davies #define WANT_MATH #include "include.h" #include "newmat.h" #include "newmatrc.h" #include "precisio.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,8); ++ExeCount; } #else #define REPORT {} #endif /************************** LU transformation ****************************/ void CroutMatrix::ludcmp() // LU decomposition from Golub & Van Loan, algorithm 3.4.1, (the "outer // product" version). // This replaces the code derived from Numerical Recipes in C in previous // versions of newmat and being row oriented runs much faster with large // matrices. { REPORT Tracer trace( "Crout(ludcmp)" ); sing = false; Real* akk = store; // runs down diagonal Real big = fabs(*akk); int mu = 0; Real* ai = akk; int k; for (k = 1; k < nrows; k++) { ai += nrows; const Real trybig = fabs(*ai); if (big < trybig) { big = trybig; mu = k; } } if (nrows) for (k = 0;;) { /* int mu1; { Real big = fabs(*akk); mu1 = k; Real* ai = akk; int i; for (i = k+1; i < nrows; i++) { ai += nrows; const Real trybig = fabs(*ai); if (big < trybig) { big = trybig; mu1 = i; } } } if (mu1 != mu) cout << k << " " << mu << " " << mu1 << endl; */ indx[k] = mu; if (mu != k) //row swap { Real* a1 = store + nrows * k; Real* a2 = store + nrows * mu; d = !d; int j = nrows; while (j--) { const Real temp = *a1; *a1++ = *a2; *a2++ = temp; } } Real diag = *akk; big = 0; mu = k + 1; if (diag != 0) { ai = akk; int i = nrows - k - 1; while (i--) { ai += nrows; Real* al = ai; Real mult = *al / diag; *al = mult; int l = nrows - k - 1; Real* aj = akk; // work out the next pivot as part of this loop // this saves a column operation if (l-- != 0) { *(++al) -= (mult * *(++aj)); const Real trybig = fabs(*al); if (big < trybig) { big = trybig; mu = nrows - i - 1; } while (l--) *(++al) -= (mult * *(++aj)); } } } else sing = true; if (++k == nrows) break; // so next line won't overflow akk += nrows + 1; } } void CroutMatrix::lubksb(Real* B, int mini) { REPORT // this has been adapted from Numerical Recipes in C. The code has been // substantially streamlined, so I do not think much of the original // copyright remains. However there is not much opportunity for // variation in the code, so it is still similar to the NR code. // I follow the NR code in skipping over initial zeros in the B vector. Tracer trace("Crout(lubksb)"); if (sing) Throw(SingularException(*this)); int i, j, ii = nrows; // ii initialised : B might be all zeros // scan for first non-zero in B for (i = 0; i < nrows; i++) { int ip = indx[i]; Real temp = B[ip]; B[ip] = B[i]; B[i] = temp; if (temp != 0.0) { ii = i; break; } } Real* bi; Real* ai; i = ii + 1; if (i < nrows) { bi = B + ii; ai = store + ii + i * nrows; for (;;) { int ip = indx[i]; Real sum = B[ip]; B[ip] = B[i]; Real* aij = ai; Real* bj = bi; j = i - ii; while (j--) sum -= *aij++ * *bj++; B[i] = sum; if (++i == nrows) break; ai += nrows; } } ai = store + nrows * nrows; for (i = nrows - 1; i >= mini; i--) { Real* bj = B+i; ai -= nrows; Real* ajx = ai+i; Real sum = *bj; Real diag = *ajx; j = nrows - i; while(--j) sum -= *(++ajx) * *(++bj); B[i] = sum / diag; } } /****************************** scalar functions ****************************/ inline Real square(Real x) { return x*x; } Real GeneralMatrix::SumSquare() const { REPORT Real sum = 0.0; int i = storage; Real* s = store; while (i--) sum += square(*s++); ((GeneralMatrix&)*this).tDelete(); return sum; } Real GeneralMatrix::SumAbsoluteValue() const { REPORT Real sum = 0.0; int i = storage; Real* s = store; while (i--) sum += fabs(*s++); ((GeneralMatrix&)*this).tDelete(); return sum; } Real GeneralMatrix::Sum() const { REPORT Real sum = 0.0; int i = storage; Real* s = store; while (i--) sum += *s++; ((GeneralMatrix&)*this).tDelete(); return sum; } // maxima and minima // There are three sets of routines // MaximumAbsoluteValue, MinimumAbsoluteValue, Maximum, Minimum // ... these find just the maxima and minima // MaximumAbsoluteValue1, MinimumAbsoluteValue1, Maximum1, Minimum1 // ... these find the maxima and minima and their locations in a // one dimensional object // MaximumAbsoluteValue2, MinimumAbsoluteValue2, Maximum2, Minimum2 // ... these find the maxima and minima and their locations in a // two dimensional object // If the matrix has no values throw an exception // If we do not want the location find the maximum or minimum on the // array stored by GeneralMatrix // This won't work for BandMatrices. We call ClearCorner for // MaximumAbsoluteValue but for the others use the AbsoluteMinimumValue2 // version and discard the location. // For one dimensional objects, when we want the location of the // maximum or minimum, work with the array stored by GeneralMatrix // For two dimensional objects where we want the location of the maximum or // minimum proceed as follows: // For rectangular matrices use the array stored by GeneralMatrix and // deduce the location from the location in the GeneralMatrix // For other two dimensional matrices use the Matrix Row routine to find the // maximum or minimum for each row. static void NullMatrixError(const GeneralMatrix* gm) { ((GeneralMatrix&)*gm).tDelete(); Throw(ProgramException("Maximum or minimum of null matrix")); } Real GeneralMatrix::MaximumAbsoluteValue() const { REPORT if (storage == 0) NullMatrixError(this); Real maxval = 0.0; int l = storage; Real* s = store; while (l--) { Real a = fabs(*s++); if (maxval < a) maxval = a; } ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::MaximumAbsoluteValue1(int& i) const { REPORT if (storage == 0) NullMatrixError(this); Real maxval = 0.0; int l = storage; Real* s = store; int li = storage; while (l--) { Real a = fabs(*s++); if (maxval <= a) { maxval = a; li = l; } } i = storage - li; ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::MinimumAbsoluteValue() const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real minval = fabs(*s++); while (l--) { Real a = fabs(*s++); if (minval > a) minval = a; } ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::MinimumAbsoluteValue1(int& i) const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real minval = fabs(*s++); int li = l; while (l--) { Real a = fabs(*s++); if (minval >= a) { minval = a; li = l; } } i = storage - li; ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::Maximum() const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real maxval = *s++; while (l--) { Real a = *s++; if (maxval < a) maxval = a; } ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::Maximum1(int& i) const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real maxval = *s++; int li = l; while (l--) { Real a = *s++; if (maxval <= a) { maxval = a; li = l; } } i = storage - li; ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::Minimum() const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real minval = *s++; while (l--) { Real a = *s++; if (minval > a) minval = a; } ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::Minimum1(int& i) const { REPORT if (storage == 0) NullMatrixError(this); int l = storage - 1; Real* s = store; Real minval = *s++; int li = l; while (l--) { Real a = *s++; if (minval >= a) { minval = a; li = l; } } i = storage - li; ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::MaximumAbsoluteValue2(int& i, int& j) const { REPORT if (storage == 0) NullMatrixError(this); Real maxval = 0.0; int nr = Nrows(); MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); for (int r = 1; r <= nr; r++) { int c; maxval = mr.MaximumAbsoluteValue1(maxval, c); if (c > 0) { i = r; j = c; } mr.Next(); } ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::MinimumAbsoluteValue2(int& i, int& j) const { REPORT if (storage == 0) NullMatrixError(this); Real minval = FloatingPointPrecision::Maximum(); int nr = Nrows(); MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); for (int r = 1; r <= nr; r++) { int c; minval = mr.MinimumAbsoluteValue1(minval, c); if (c > 0) { i = r; j = c; } mr.Next(); } ((GeneralMatrix&)*this).tDelete(); return minval; } Real GeneralMatrix::Maximum2(int& i, int& j) const { REPORT if (storage == 0) NullMatrixError(this); Real maxval = -FloatingPointPrecision::Maximum(); int nr = Nrows(); MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); for (int r = 1; r <= nr; r++) { int c; maxval = mr.Maximum1(maxval, c); if (c > 0) { i = r; j = c; } mr.Next(); } ((GeneralMatrix&)*this).tDelete(); return maxval; } Real GeneralMatrix::Minimum2(int& i, int& j) const { REPORT if (storage == 0) NullMatrixError(this); Real minval = FloatingPointPrecision::Maximum(); int nr = Nrows(); MatrixRow mr((GeneralMatrix*)this, LoadOnEntry+DirectPart); for (int r = 1; r <= nr; r++) { int c; minval = mr.Minimum1(minval, c); if (c > 0) { i = r; j = c; } mr.Next(); } ((GeneralMatrix&)*this).tDelete(); return minval; } Real Matrix::MaximumAbsoluteValue2(int& i, int& j) const { REPORT int k; Real m = GeneralMatrix::MaximumAbsoluteValue1(k); k--; i = k / Ncols(); j = k - i * Ncols(); i++; j++; return m; } Real Matrix::MinimumAbsoluteValue2(int& i, int& j) const { REPORT int k; Real m = GeneralMatrix::MinimumAbsoluteValue1(k); k--; i = k / Ncols(); j = k - i * Ncols(); i++; j++; return m; } Real Matrix::Maximum2(int& i, int& j) const { REPORT int k; Real m = GeneralMatrix::Maximum1(k); k--; i = k / Ncols(); j = k - i * Ncols(); i++; j++; return m; } Real Matrix::Minimum2(int& i, int& j) const { REPORT int k; Real m = GeneralMatrix::Minimum1(k); k--; i = k / Ncols(); j = k - i * Ncols(); i++; j++; return m; } Real SymmetricMatrix::SumSquare() const { REPORT Real sum1 = 0.0; Real sum2 = 0.0; Real* s = store; int nr = nrows; for (int i = 0; iSumSquare(); return s; } Real BaseMatrix::NormFrobenius() const { REPORT return sqrt(SumSquare()); } Real BaseMatrix::SumAbsoluteValue() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->SumAbsoluteValue(); return s; } Real BaseMatrix::Sum() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Sum(); return s; } Real BaseMatrix::MaximumAbsoluteValue() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MaximumAbsoluteValue(); return s; } Real BaseMatrix::MaximumAbsoluteValue1(int& i) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MaximumAbsoluteValue1(i); return s; } Real BaseMatrix::MaximumAbsoluteValue2(int& i, int& j) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MaximumAbsoluteValue2(i, j); return s; } Real BaseMatrix::MinimumAbsoluteValue() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MinimumAbsoluteValue(); return s; } Real BaseMatrix::MinimumAbsoluteValue1(int& i) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MinimumAbsoluteValue1(i); return s; } Real BaseMatrix::MinimumAbsoluteValue2(int& i, int& j) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->MinimumAbsoluteValue2(i, j); return s; } Real BaseMatrix::Maximum() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Maximum(); return s; } Real BaseMatrix::Maximum1(int& i) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Maximum1(i); return s; } Real BaseMatrix::Maximum2(int& i, int& j) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Maximum2(i, j); return s; } Real BaseMatrix::Minimum() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Minimum(); return s; } Real BaseMatrix::Minimum1(int& i) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Minimum1(i); return s; } Real BaseMatrix::Minimum2(int& i, int& j) const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); Real s = gm->Minimum2(i, j); return s; } Real DotProduct(const Matrix& A, const Matrix& B) { REPORT int n = A.storage; if (n != B.storage) Throw(IncompatibleDimensionsException(A,B)); Real sum = 0.0; Real* a = A.store; Real* b = B.store; while (n--) sum += *a++ * *b++; return sum; } Real Matrix::Trace() const { REPORT Tracer trace("Trace"); int i = nrows; int d = i+1; if (i != ncols) Throw(NotSquareException(*this)); Real sum = 0.0; Real* s = store; // while (i--) { sum += *s; s += d; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += d; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real DiagonalMatrix::Trace() const { REPORT int i = nrows; Real sum = 0.0; Real* s = store; while (i--) sum += *s++; ((GeneralMatrix&)*this).tDelete(); return sum; } Real SymmetricMatrix::Trace() const { REPORT int i = nrows; Real sum = 0.0; Real* s = store; int j = 2; // while (i--) { sum += *s; s += j++; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += j++; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real LowerTriangularMatrix::Trace() const { REPORT int i = nrows; Real sum = 0.0; Real* s = store; int j = 2; // while (i--) { sum += *s; s += j++; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += j++; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real UpperTriangularMatrix::Trace() const { REPORT int i = nrows; Real sum = 0.0; Real* s = store; while (i) { sum += *s; s += i--; } // won t cause a problem ((GeneralMatrix&)*this).tDelete(); return sum; } Real BandMatrix::Trace() const { REPORT int i = nrows; int w = lower+upper+1; Real sum = 0.0; Real* s = store+lower; // while (i--) { sum += *s; s += w; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += w; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real SymmetricBandMatrix::Trace() const { REPORT int i = nrows; int w = lower+1; Real sum = 0.0; Real* s = store+lower; // while (i--) { sum += *s; s += w; } if (i) for (;;) { sum += *s; if (!(--i)) break; s += w; } ((GeneralMatrix&)*this).tDelete(); return sum; } Real IdentityMatrix::Trace() const { Real sum = *store * nrows; ((GeneralMatrix&)*this).tDelete(); return sum; } Real BaseMatrix::Trace() const { REPORT MatrixType Diag = MatrixType::Dg; Diag.SetDataLossOK(); GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(Diag); Real sum = gm->Trace(); return sum; } void LogAndSign::operator*=(Real x) { if (x > 0.0) { log_value += log(x); } else if (x < 0.0) { log_value += log(-x); sign = -sign; } else sign = 0; } void LogAndSign::PowEq(int k) { if (sign) { log_value *= k; if ( (k & 1) == 0 ) sign = 1; } } Real LogAndSign::Value() const { Tracer et("LogAndSign::Value"); if (log_value >= FloatingPointPrecision::LnMaximum()) Throw(OverflowException("Overflow in exponential")); return sign * exp(log_value); } LogAndSign::LogAndSign(Real f) { if (f == 0.0) { log_value = 0.0; sign = 0; return; } else if (f < 0.0) { sign = -1; f = -f; } else sign = 1; log_value = log(f); } LogAndSign DiagonalMatrix::LogDeterminant() const { REPORT int i = nrows; LogAndSign sum; Real* s = store; while (i--) sum *= *s++; ((GeneralMatrix&)*this).tDelete(); return sum; } LogAndSign LowerTriangularMatrix::LogDeterminant() const { REPORT int i = nrows; LogAndSign sum; Real* s = store; int j = 2; // while (i--) { sum *= *s; s += j++; } if (i) for(;;) { sum *= *s; if (!(--i)) break; s += j++; } ((GeneralMatrix&)*this).tDelete(); return sum; } LogAndSign UpperTriangularMatrix::LogDeterminant() const { REPORT int i = nrows; LogAndSign sum; Real* s = store; while (i) { sum *= *s; s += i--; } ((GeneralMatrix&)*this).tDelete(); return sum; } LogAndSign IdentityMatrix::LogDeterminant() const { REPORT int i = nrows; LogAndSign sum; if (i > 0) { sum = *store; sum.PowEq(i); } ((GeneralMatrix&)*this).tDelete(); return sum; } LogAndSign BaseMatrix::LogDeterminant() const { REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); LogAndSign sum = gm->LogDeterminant(); return sum; } LogAndSign GeneralMatrix::LogDeterminant() const { REPORT Tracer tr("LogDeterminant"); if (nrows != ncols) Throw(NotSquareException(*this)); CroutMatrix C(*this); return C.LogDeterminant(); } LogAndSign CroutMatrix::LogDeterminant() const { REPORT if (sing) return 0.0; int i = nrows; int dd = i+1; LogAndSign sum; Real* s = store; if (i) for(;;) { sum *= *s; if (!(--i)) break; s += dd; } if (!d) sum.ChangeSign(); return sum; } Real BaseMatrix::Determinant() const { REPORT Tracer tr("Determinant"); REPORT GeneralMatrix* gm = ((BaseMatrix&)*this).Evaluate(); LogAndSign ld = gm->LogDeterminant(); return ld.Value(); } LinearEquationSolver::LinearEquationSolver(const BaseMatrix& bm) { gm = ( ((BaseMatrix&)bm).Evaluate() )->MakeSolver(); if (gm==&bm) { REPORT gm = gm->Image(); } // want a copy if *gm is actually bm else { REPORT gm->Protect(); } } #ifdef use_namespace } #endif newmat-1.10.4/newmat9.cpp0000644001161000116100000000312010404726606013365 0ustar rzrrzr//$$ newmat9.cpp Input and output // Copyright (C) 1991,2,3,4: R B Davies #define WANT_FSTREAM #include "include.h" #include "newmat.h" #include "newmatio.h" #include "newmatrc.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,9); ++ExeCount; } #else #define REPORT {} #endif // for G++ 3.01 #ifndef ios_format_flags #define ios_format_flags long #endif ostream& operator<<(ostream& s, const BaseMatrix& X) { GeneralMatrix* gm = ((BaseMatrix&)X).Evaluate(); operator<<(s, *gm); gm->tDelete(); return s; } ostream& operator<<(ostream& s, const GeneralMatrix& X) { MatrixRow mr((GeneralMatrix*)&X, LoadOnEntry); int w = s.width(); int nr = X.Nrows(); ios_format_flags f = s.flags(); s.setf(ios::fixed, ios::floatfield); for (int i=1; i<=nr; i++) { int skip = mr.skip; int storage = mr.storage; Real* store = mr.data; skip *= w+1; while (skip--) s << " "; while (storage--) { s.width(w); s << *store++ << " "; } // while (storage--) s << setw(w) << *store++ << " "; mr.Next(); s << "\n"; } s << flush; s.flags(f); return s; } // include this stuff if you are using an old version of G++ // with an incomplete io library /* ostream& operator<<(ostream& os, Omanip_precision i) { os.precision(i.x); return os; } Omanip_precision setprecision(int i) { return Omanip_precision(i); } ostream& operator<<(ostream& os, Omanip_width i) { os.width(i.x); return os; } Omanip_width setw(int i) { return Omanip_width(i); } */ #ifdef use_namespace } #endif newmat-1.10.4/newmatap.h0000644001161000116100000001100107416412320013251 0ustar rzrrzr//$$ newmatap.h definition file for matrix package applications // Copyright (C) 1991,2,3,4,8: R B Davies #ifndef NEWMATAP_LIB #define NEWMATAP_LIB 0 #include "newmat.h" #ifdef use_namespace namespace NEWMAT { #endif // ************************** applications *****************************/ void QRZT(Matrix&, LowerTriangularMatrix&); void QRZT(const Matrix&, Matrix&, Matrix&); void QRZ(Matrix&, UpperTriangularMatrix&); void QRZ(const Matrix&, Matrix&, Matrix&); inline void HHDecompose(Matrix& X, LowerTriangularMatrix& L) { QRZT(X,L); } inline void HHDecompose(const Matrix& X, Matrix& Y, Matrix& M) { QRZT(X, Y, M); } ReturnMatrix Cholesky(const SymmetricMatrix&); ReturnMatrix Cholesky(const SymmetricBandMatrix&); void SVD(const Matrix&, DiagonalMatrix&, Matrix&, Matrix&, bool=true, bool=true); void SVD(const Matrix&, DiagonalMatrix&); inline void SVD(const Matrix& A, DiagonalMatrix& D, Matrix& U, bool withU = true) { SVD(A, D, U, U, withU, false); } void SortSV(DiagonalMatrix& D, Matrix& U, bool ascending = false); void SortSV(DiagonalMatrix& D, Matrix& U, Matrix& V, bool ascending = false); void Jacobi(const SymmetricMatrix&, DiagonalMatrix&); void Jacobi(const SymmetricMatrix&, DiagonalMatrix&, SymmetricMatrix&); void Jacobi(const SymmetricMatrix&, DiagonalMatrix&, Matrix&); void Jacobi(const SymmetricMatrix&, DiagonalMatrix&, SymmetricMatrix&, Matrix&, bool=true); void EigenValues(const SymmetricMatrix&, DiagonalMatrix&); void EigenValues(const SymmetricMatrix&, DiagonalMatrix&, SymmetricMatrix&); void EigenValues(const SymmetricMatrix&, DiagonalMatrix&, Matrix&); class SymmetricEigenAnalysis // not implemented yet { public: SymmetricEigenAnalysis(const SymmetricMatrix&); private: DiagonalMatrix diag; DiagonalMatrix offdiag; SymmetricMatrix backtransform; FREE_CHECK(SymmetricEigenAnalysis) }; void SortAscending(GeneralMatrix&); void SortDescending(GeneralMatrix&); // class for deciding which fft to use and containing new fft function class FFT_Controller { public: static bool OnlyOldFFT; static bool ar_1d_ft (int PTS, Real* X, Real *Y); static bool CanFactor(int PTS); }; void FFT(const ColumnVector&, const ColumnVector&, ColumnVector&, ColumnVector&); void FFTI(const ColumnVector&, const ColumnVector&, ColumnVector&, ColumnVector&); void RealFFT(const ColumnVector&, ColumnVector&, ColumnVector&); void RealFFTI(const ColumnVector&, const ColumnVector&, ColumnVector&); void DCT_II(const ColumnVector&, ColumnVector&); void DCT_II_inverse(const ColumnVector&, ColumnVector&); void DST_II(const ColumnVector&, ColumnVector&); void DST_II_inverse(const ColumnVector&, ColumnVector&); void DCT(const ColumnVector&, ColumnVector&); void DCT_inverse(const ColumnVector&, ColumnVector&); void DST(const ColumnVector&, ColumnVector&); void DST_inverse(const ColumnVector&, ColumnVector&); // This class is used by the new FFT program // Suppose an integer is expressed as a sequence of digits with each // digit having a different radix. // This class supposes we are counting with this multi-radix number // but also keeps track of the number with the digits (and radices) // reversed. // The integer starts at zero // operator++() increases it by 1 // Counter gives the number of increments // Reverse() gives the value with the digits in reverse order // Swap is true if reverse is less than counter // Finish is true when we have done a complete cycle and are back at zero class MultiRadixCounter { const SimpleIntArray& Radix; // radix of each digit // n-1 highest order, 0 lowest order SimpleIntArray& Value; // value of each digit const int n; // number of digits int reverse; // value when order of digits is reversed int product; // product of radices int counter; // counter bool finish; // true when we have gone over whole range public: MultiRadixCounter(int nx, const SimpleIntArray& rx, SimpleIntArray& vx); void operator++(); // increment the multi-radix counter bool Swap() const { return reverse < counter; } bool Finish() const { return finish; } int Reverse() const { return reverse; } int Counter() const { return counter; } }; #ifdef use_namespace } #endif #endif // body file: cholesky.cpp // body file: evalue.cpp // body file: fft.cpp // body file: hholder.cpp // body file: jacobi.cpp // body file: newfft.cpp // body file: sort.cpp // body file: svd.cpp newmat-1.10.4/newmatex.cpp0000644001161000116100000002105610406436225013636 0ustar rzrrzr//$$ newmatex.cpp Exception handler // Copyright (C) 1992,3,4,7: R B Davies #define WANT_STREAM // include.h will get stream fns #include "include.h" // include standard files #include "newmat.h" #ifdef use_namespace namespace NEWMAT { #endif unsigned long OverflowException::Select; unsigned long SingularException::Select; unsigned long NPDException::Select; unsigned long ConvergenceException::Select; unsigned long ProgramException::Select; unsigned long IndexException::Select; unsigned long VectorException::Select; unsigned long NotSquareException::Select; unsigned long SubMatrixDimensionException::Select; unsigned long IncompatibleDimensionsException::Select; unsigned long NotDefinedException::Select; unsigned long CannotBuildException::Select; unsigned long InternalException::Select; static void MatrixDetails(const GeneralMatrix& A) // write matrix details to Exception buffer { MatrixBandWidth bw = A.BandWidth(); int ubw = bw.upper; int lbw = bw.lower; BaseException::AddMessage("MatrixType = "); BaseException::AddMessage(A.Type().Value()); BaseException::AddMessage(" # Rows = "); BaseException::AddInt(A.Nrows()); BaseException::AddMessage("; # Cols = "); BaseException::AddInt(A.Ncols()); if (lbw >=0) { BaseException::AddMessage("; lower BW = "); BaseException::AddInt(lbw); } if (ubw >=0) { BaseException::AddMessage("; upper BW = "); BaseException::AddInt(ubw); } BaseException::AddMessage("\n"); } NPDException::NPDException(const GeneralMatrix& A) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: matrix not positive definite\n\n"); MatrixDetails(A); Tracer::AddTrace(); } SingularException::SingularException(const GeneralMatrix& A) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: matrix is singular\n\n"); MatrixDetails(A); Tracer::AddTrace(); } ConvergenceException::ConvergenceException(const GeneralMatrix& A) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: process fails to converge\n\n"); MatrixDetails(A); Tracer::AddTrace(); } ConvergenceException::ConvergenceException(const char* c) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); if (c) Tracer::AddTrace(); } OverflowException::OverflowException(const char* c) : Runtime_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); if (c) Tracer::AddTrace(); } ProgramException::ProgramException(const char* c) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); if (c) Tracer::AddTrace(); } ProgramException::ProgramException(const char* c, const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); MatrixDetails(A); if (c) Tracer::AddTrace(); } ProgramException::ProgramException(const char* c, const GeneralMatrix& A, const GeneralMatrix& B) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\n\n"); MatrixDetails(A); MatrixDetails(B); if (c) Tracer::AddTrace(); } ProgramException::ProgramException(const char* c, MatrixType a, MatrixType b) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(c); AddMessage("\nMatrixTypes = "); AddMessage(a.Value()); AddMessage("; "); AddMessage(b.Value()); AddMessage("\n\n"); if (c) Tracer::AddTrace(); } VectorException::VectorException() : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: cannot convert matrix to vector\n\n"); Tracer::AddTrace(); } VectorException::VectorException(const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: cannot convert matrix to vector\n\n"); MatrixDetails(A); Tracer::AddTrace(); } NotSquareException::NotSquareException(const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: matrix is not square\n\n"); MatrixDetails(A); Tracer::AddTrace(); } SubMatrixDimensionException::SubMatrixDimensionException() : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: incompatible submatrix dimension\n\n"); Tracer::AddTrace(); } IncompatibleDimensionsException::IncompatibleDimensionsException() : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: incompatible dimensions\n\n"); Tracer::AddTrace(); } IncompatibleDimensionsException::IncompatibleDimensionsException (const GeneralMatrix& A, const GeneralMatrix& B) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: incompatible dimensions\n\n"); MatrixDetails(A); MatrixDetails(B); Tracer::AddTrace(); } NotDefinedException::NotDefinedException(const char* op, const char* matrix) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: "); AddMessage(op); AddMessage(" not defined for "); AddMessage(matrix); AddMessage("\n\n"); Tracer::AddTrace(); } CannotBuildException::CannotBuildException(const char* matrix) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: cannot build matrix type "); AddMessage(matrix); AddMessage("\n\n"); Tracer::AddTrace(); } IndexException::IndexException(int i, const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: index error: requested index = "); AddInt(i); AddMessage("\n\n"); MatrixDetails(A); Tracer::AddTrace(); } IndexException::IndexException(int i, int j, const GeneralMatrix& A) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: index error: requested indices = "); AddInt(i); AddMessage(", "); AddInt(j); AddMessage("\n\n"); MatrixDetails(A); Tracer::AddTrace(); } IndexException::IndexException(int i, const GeneralMatrix& A, bool) : Logic_error() { Select = BaseException::Select; AddMessage("detected by Newmat: element error: requested index (wrt 0) = "); AddInt(i); AddMessage("\n\n"); MatrixDetails(A); Tracer::AddTrace(); } IndexException::IndexException(int i, int j, const GeneralMatrix& A, bool) : Logic_error() { Select = BaseException::Select; AddMessage( "detected by Newmat: element error: requested indices (wrt 0) = "); AddInt(i); AddMessage(", "); AddInt(j); AddMessage("\n\n"); MatrixDetails(A); Tracer::AddTrace(); } InternalException::InternalException(const char* c) : Logic_error() { Select = BaseException::Select; AddMessage("internal error detected by Newmat: please inform author\n"); AddMessage(c); AddMessage("\n\n"); Tracer::AddTrace(); } /************************* ExeCounter functions *****************************/ #ifdef DO_REPORT int ExeCounter::nreports; // will be set to zero ExeCounter::ExeCounter(int xl, int xf) : line(xl), fileid(xf), nexe(0) {} ExeCounter::~ExeCounter() { nreports++; cout << "REPORT " << setw(6) << nreports << " " << setw(6) << fileid << " " << setw(6) << line << " " << setw(6) << nexe << "\n"; } #endif /**************************** error handler *******************************/ void MatrixErrorNoSpace(void* v) { if (!v) Throw(Bad_alloc()); } // throw exception if v is null /************************* miscellanous errors ***************************/ void CroutMatrix::GetRow(MatrixRowCol&) { Throw(NotDefinedException("GetRow","Crout")); } void CroutMatrix::GetCol(MatrixRowCol&) { Throw(NotDefinedException("GetCol","Crout")); } void CroutMatrix::operator=(const BaseMatrix&) { Throw(NotDefinedException("=","Crout")); } void BandLUMatrix::GetRow(MatrixRowCol&) { Throw(NotDefinedException("GetRow","BandLUMatrix")); } void BandLUMatrix::GetCol(MatrixRowCol&) { Throw(NotDefinedException("GetCol","BandLUMatrix")); } void BandLUMatrix::operator=(const BaseMatrix&) { Throw(NotDefinedException("=","BandLUMatrix")); } void BaseMatrix::IEQND() const { Throw(NotDefinedException("inequalities", "matrices")); } #ifdef TEMPS_DESTROYED_QUICKLY_R ReturnMatrixX::ReturnMatrixX(const ReturnMatrixX& tm) : gm(tm.gm) { Throw(ProgramException("ReturnMatrixX error")); } #endif #ifdef use_namespace } #endif newmat-1.10.4/newmatio.h0000644001161000116100000000167107314306016013275 0ustar rzrrzr//$$ newmatio.h definition file for matrix package input/output // Copyright (C) 1991,2,3,4: R B Davies #ifndef NEWMATIO_LIB #define NEWMATIO_LIB 0 #ifndef WANT_STREAM #define WANT_STREAM #endif #include "newmat.h" #ifdef use_namespace namespace NEWMAT { #endif /**************************** input/output *****************************/ ostream& operator<<(ostream&, const BaseMatrix&); ostream& operator<<(ostream&, const GeneralMatrix&); /* Use in some old versions of G++ without complete iomanipulators class Omanip_precision { int x; public: Omanip_precision(int i) : x(i) {} friend ostream& operator<<(ostream& os, Omanip_precision i); }; Omanip_precision setprecision(int i); class Omanip_width { int x; public: Omanip_width(int i) : x(i) {} friend ostream& operator<<(ostream& os, Omanip_width i); }; Omanip_width setw(int i); */ #ifdef use_namespace } #endif #endif // body file: newmat9.cpp newmat-1.10.4/newmatnl.cpp0000644001161000116100000001602106525237512013634 0ustar rzrrzr//$$ newmatnl.cpp Non-linear optimisation // Copyright (C) 1993,4,5,6: R B Davies #define WANT_MATH #define WANT_STREAM #include "newmatap.h" #include "newmatnl.h" #ifdef use_namespace namespace NEWMAT { #endif void FindMaximum2::Fit(ColumnVector& Theta, int n_it) { Tracer tr("FindMaximum2::Fit"); enum State {Start, Restart, Continue, Interpolate, Extrapolate, Fail, Convergence}; State TheState = Start; Real z,w,x,x2,g,l1,l2,l3,d1,d2=0,d3; ColumnVector Theta1, Theta2, Theta3; int np = Theta.Nrows(); ColumnVector H1(np), H3, HP(np), K, K1(np); bool oorg, conv; int counter = 0; Theta1 = Theta; HP = 0.0; g = 0.0; // This is really a set of gotos and labels, but they do not work // correctly in AT&T C++ and Sun 4.01 C++. for(;;) { switch (TheState) { case Start: tr.ReName("FindMaximum2::Fit/Start"); Value(Theta1, true, l1, oorg); if (oorg) Throw(ProgramException("invalid starting value\n")); case Restart: tr.ReName("FindMaximum2::Fit/ReStart"); conv = NextPoint(H1, d1); if (conv) { TheState = Convergence; break; } if (counter++ > n_it) { TheState = Fail; break; } z = 1.0 / sqrt(d1); H3 = H1 * z; K = (H3 - HP) * g; HP = H3; g = 0.0; // de-activate to use curved projection if (g==0.0) K1 = 0.0; else K1 = K * 0.2 + K1 * 0.6; // (K - K1) * alpha + K1 * (1 - alpha) // = K * alpha + K1 * (1 - 2 * alpha) K = K1 * d1; g = z; case Continue: tr.ReName("FindMaximum2::Fit/Continue"); Theta2 = Theta1 + H1 + K; Value(Theta2, false, l2, oorg); if (counter++ > n_it) { TheState = Fail; break; } if (oorg) { H1 *= 0.5; K *= 0.25; d1 *= 0.5; g *= 2.0; TheState = Continue; break; } d2 = LastDerivative(H1 + K * 2.0); case Interpolate: tr.ReName("FindMaximum2::Fit/Interpolate"); z = d1 + d2 - 3.0 * (l2 - l1); w = z * z - d1 * d2; if (w < 0.0) { TheState = Extrapolate; break; } w = z + sqrt(w); if (1.5 * w + d1 < 0.0) { TheState = Extrapolate; break; } if (d2 > 0.0 && l2 > l1 && w > 0.0) { TheState = Extrapolate; break; } x = d1 / (w + d1); x2 = x * x; g /= x; Theta3 = Theta1 + H1 * x + K * x2; Value(Theta3, true, l3, oorg); if (counter++ > n_it) { TheState = Fail; break; } if (oorg) { if (x <= 1.0) { x *= 0.5; x2 = x*x; g *= 2.0; d1 *= x; H1 *= x; K *= x2; } else { x = 0.5 * (x-1.0); x2 = x*x; Theta1 = Theta2; H1 = (H1 + K * 2.0) * x; K *= x2; g = 0.0; d1 = x * d2; l1 = l2; } TheState = Continue; break; } if (l3 >= l1 && l3 >= l2) { Theta1 = Theta3; l1 = l3; TheState = Restart; break; } d3 = LastDerivative(H1 + K * 2.0); if (l1 > l2) { H1 *= x; K *= x2; Theta2 = Theta3; d1 *= x; d2 = d3*x; } else { Theta1 = Theta2; Theta2 = Theta3; x -= 1.0; x2 = x*x; g = 0.0; H1 = (H1 + K * 2.0) * x; K *= x2; l1 = l2; l2 = l3; d1 = x*d2; d2 = x*d3; if (d1 <= 0.0) { TheState = Start; break; } } TheState = Interpolate; break; case Extrapolate: tr.ReName("FindMaximum2::Fit/Extrapolate"); Theta1 = Theta2; g = 0.0; K *= 4.0; H1 = (H1 * 2.0 + K); d1 = 2.0 * d2; l1 = l2; TheState = Continue; break; case Fail: Throw(ConvergenceException(Theta)); case Convergence: Theta = Theta1; return; } } } void NonLinearLeastSquares::Value (const ColumnVector& Parameters, bool, Real& v, bool& oorg) { Tracer tr("NonLinearLeastSquares::Value"); Y.ReSize(n_obs); X.ReSize(n_obs,n_param); // put the fitted values in Y, the derivatives in X. Pred.Set(Parameters); if (!Pred.IsValid()) { oorg=true; return; } for (int i=1; i<=n_obs; i++) { Y(i) = Pred(i); X.Row(i) = Pred.Derivatives(); } if (!Pred.IsValid()) { oorg=true; return; } // check afterwards as well Y = *DataPointer - Y; Real ssq = Y.SumSquare(); errorvar = ssq / (n_obs - n_param); cout << "\n" << setw(15) << setprecision(10) << " " << errorvar; Derivs = Y.t() * X; // get the derivative and stash it oorg = false; v = -0.5 * ssq; } bool NonLinearLeastSquares::NextPoint(ColumnVector& Adj, Real& test) { Tracer tr("NonLinearLeastSquares::NextPoint"); QRZ(X, U); QRZ(X, Y, M); // do the QR decomposition test = M.SumSquare(); cout << " " << setw(15) << setprecision(10) << test << " " << Y.SumSquare() / (n_obs - n_param); Adj = U.i() * M; if (test < errorvar * criterion) return true; else return false; } Real NonLinearLeastSquares::LastDerivative(const ColumnVector& H) { return (Derivs * H).AsScalar(); } void NonLinearLeastSquares::Fit(const ColumnVector& Data, ColumnVector& Parameters) { Tracer tr("NonLinearLeastSquares::Fit"); n_param = Parameters.Nrows(); n_obs = Data.Nrows(); DataPointer = &Data; FindMaximum2::Fit(Parameters, Lim); cout << "\nConverged\n"; } void NonLinearLeastSquares::MakeCovariance() { if (Covariance.Nrows()==0) { UpperTriangularMatrix UI = U.i(); Covariance << UI * UI.t() * errorvar; SE << Covariance; // get diagonals for (int i = 1; i<=n_param; i++) SE(i) = sqrt(SE(i)); } } void NonLinearLeastSquares::GetStandardErrors(ColumnVector& SEX) { MakeCovariance(); SEX = SE.AsColumn(); } void NonLinearLeastSquares::GetCorrelations(SymmetricMatrix& Corr) { MakeCovariance(); Corr << SE.i() * Covariance * SE.i(); } void NonLinearLeastSquares::GetHatDiagonal(DiagonalMatrix& Hat) const { Hat.ReSize(n_obs); for (int i = 1; i<=n_obs; i++) Hat(i) = X.Row(i).SumSquare(); } // the MLE_D_FI routines void MLE_D_FI::Value (const ColumnVector& Parameters, bool wg, Real& v, bool& oorg) { Tracer tr("MLE_D_FI::Value"); if (!LL.IsValid(Parameters,wg)) { oorg=true; return; } v = LL.LogLikelihood(); if (!LL.IsValid()) { oorg=true; return; } // check validity again cout << "\n" << setw(20) << setprecision(10) << v; oorg = false; Derivs = LL.Derivatives(); // Get derivatives } bool MLE_D_FI::NextPoint(ColumnVector& Adj, Real& test) { Tracer tr("MLE_D_FI::NextPoint"); SymmetricMatrix FI = LL.FI(); LT = Cholesky(FI); ColumnVector Adj1 = LT.i() * Derivs; Adj = LT.t().i() * Adj1; test = SumSquare(Adj1); cout << " " << setw(20) << setprecision(10) << test; return (test < Criterion); } Real MLE_D_FI::LastDerivative(const ColumnVector& H) { return (Derivs.t() * H).AsScalar(); } void MLE_D_FI::Fit(ColumnVector& Parameters) { Tracer tr("MLE_D_FI::Fit"); FindMaximum2::Fit(Parameters,Lim); cout << "\nConverged\n"; } void MLE_D_FI::MakeCovariance() { if (Covariance.Nrows()==0) { LowerTriangularMatrix LTI = LT.i(); Covariance << LTI.t() * LTI; SE << Covariance; // get diagonal int n = Covariance.Nrows(); for (int i=1; i <= n; i++) SE(i) = sqrt(SE(i)); } } void MLE_D_FI::GetStandardErrors(ColumnVector& SEX) { MakeCovariance(); SEX = SE.AsColumn(); } void MLE_D_FI::GetCorrelations(SymmetricMatrix& Corr) { MakeCovariance(); Corr << SE.i() * Covariance * SE.i(); } #ifdef use_namespace } #endif newmat-1.10.4/newmatnl.h0000644001161000116100000002553207314306042013300 0ustar rzrrzr//$$ newmatnl.h definition file for non-linear optimisation // Copyright (C) 1993,4,5: R B Davies #ifndef NEWMATNL_LIB #define NEWMATNL_LIB 0 #include "newmat.h" #ifdef use_namespace namespace NEWMAT { #endif /* This is a beginning of a series of classes for non-linear optimisation. At present there are two classes. FindMaximum2 is the basic optimisation strategy when one is doing an optimisation where one has first derivatives and estimates of the second derivatives. Class NonLinearLeastSquares is derived from FindMaximum2. This provides the functions that calculate function values and derivatives. A third class is now added. This is for doing maximum-likelihood when you have first derviatives and something like the Fisher Information matrix (eg the variance covariance matrix of the first derivatives or minus the second derivatives - this matrix is assumed to be positive definite). class FindMaximum2 Suppose T is the ColumnVector of parameters, F(T) the function we want to maximise, D(T) the ColumnVector of derivatives of F with respect to T, and S(T) the matrix of second derivatives. Then the basic iteration is given a value of T, update it to T - S.i() * D where .i() denotes inverse. If F was quadratic this would give exactly the right answer (except it might get a minimum rather than a maximum). Since F is not usually quadratic, the simple procedure would be to recalculate S and D with the new value of T and keep iterating until the process converges. This is known as the method of conjugate gradients. In practice, this method may not converge. FindMaximum2 considers an iteration of the form T - x * S.i() * D where x is a number. It tries x = 1 and uses the values of F and its slope with respect to x at x = 0 and x = 1 to fit a cubic in x. It then choses x to maximise the resulting function. This gives our new value of T. The program checks that the value of F is getting better and carries out a variety of strategies if it is not. The program also has a second strategy. If the successive values of T seem to be lying along a curve - eg we are following along a curved ridge, the program will try to fit this ridge and project along it. This does not work at present and is commented out. FindMaximum2 has three virtual functions which need to be over-ridden by a derived class. void Value(const ColumnVector& T, bool wg, Real& f, bool& oorg); T is the column vector of parameters. The function returns the value of the function to f, but may instead set oorg to true if the parameter values are not valid. If wg is true it may also calculate and store the second derivative information. bool NextPoint(ColumnVector& H, Real& d); Using the value of T provided in the previous call of Value, find the conjugate gradients adjustment to T, that is - S.i() * D. Also return d = D.t() * S.i() * D. NextPoint should return true if it considers that the process has converged (d very small) and false otherwise. The previous call of Value will have set wg to true, so that S will be available. Real LastDerivative(const ColumnVector& H); Return the scalar product of H and the vector of derivatives at the last value of T. The function Fit is the function that calls the iteration. void Fit(ColumnVector&, int); The arguments are the trial parameter values as a ColumnVector and the maximum number of iterations. The program calls a DataException if the initial parameters are not valid and a ConvergenceException if the process fails to converge. class NonLinearLeastSquares This class is derived from FindMaximum2 and carries out a non-linear least squares fit. It uses a QR decomposition to carry out the operations required by FindMaximum2. A prototype class R1_Col_I_D is provided. The user needs to derive a class from this which includes functions the predicted value of each observation its derivatives. An object from this class has to be provided to class NonLinearLeastSquares. Suppose we observe n normal random variables with the same unknown variance and such the i-th one has expected value given by f(i,P) where P is a column vector of unknown parameters and f is a known function. We wish to estimate P. First derive a class from R1_Col_I_D and override Real operator()(int i) to give the value of the function f in terms of i and the ColumnVector para defined in class R1_CoL_I_D. Also override ReturnMatrix Derivatives() to give the derivates of f at para and the value of i used in the preceeding call to operator(). Return the result as a RowVector. Construct an object from this class. Suppose in what follows it is called pred. Now constuct a NonLinearLeastSquaresObject accessing pred and optionally an iteration limit and an accuracy critierion. NonLinearLeastSquares NLLS(pred, 1000, 0.0001); The accuracy critierion should be somewhat less than one and 0.0001 is about the smallest sensible value. Define a ColumnVector P containing a guess at the value of the unknown parameter, and a ColumnVector Y containing the unknown data. Call NLLS.Fit(Y,P); If the process converges, P will contain the estimates of the unknown parameters. If it does not converge an exception will be generated. The following member functions can be called after you have done a fit. Real ResidualVariance() const; The estimate of the variance of the observations. void GetResiduals(ColumnVector& Z) const; The residuals of the individual observations. void GetStandardErrors(ColumnVector&); The standard errors of the observations. void GetCorrelations(SymmetricMatrix&); The correlations of the observations. void GetHatDiagonal(DiagonalMatrix&) const; Forms a diagonal matrix of values between 0 and 1. If the i-th value is larger than, say 0.2, then the i-th data value could have an undue influence on your estimates. */ class FindMaximum2 { virtual void Value(const ColumnVector&, bool, Real&, bool&) = 0; virtual bool NextPoint(ColumnVector&, Real&) = 0; virtual Real LastDerivative(const ColumnVector&) = 0; public: void Fit(ColumnVector&, int); virtual ~FindMaximum2() {} // to keep gnu happy }; class R1_Col_I_D { // The prototype for a Real function of a ColumnVector and an // integer. // You need to derive your function from this one and put in your // function for operator() and Derivatives() at least. // You may also want to set up a constructor to enter in additional // parameter values (that will not vary during the solve). protected: ColumnVector para; // Current x value public: virtual bool IsValid() { return true; } // is the current x value OK virtual Real operator()(int i) = 0; // i-th function value at current para virtual void Set(const ColumnVector& X) { para = X; } // set current para bool IsValid(const ColumnVector& X) { Set(X); return IsValid(); } // set para, check OK Real operator()(int i, const ColumnVector& X) { Set(X); return operator()(i); } // set para, return value virtual ReturnMatrix Derivatives() = 0; // return derivatives as RowVector virtual ~R1_Col_I_D() {} // to keep gnu happy }; class NonLinearLeastSquares : public FindMaximum2 { // these replace the corresponding functions in FindMaximum2 void Value(const ColumnVector&, bool, Real&, bool&); bool NextPoint(ColumnVector&, Real&); Real LastDerivative(const ColumnVector&); Matrix X; // the things we need to do the ColumnVector Y; // QR triangularisation UpperTriangularMatrix U; // see the write-up in newmata.txt ColumnVector M; Real errorvar, criterion; int n_obs, n_param; const ColumnVector* DataPointer; RowVector Derivs; SymmetricMatrix Covariance; DiagonalMatrix SE; R1_Col_I_D& Pred; // Reference to predictor object int Lim; // maximum number of iterations public: NonLinearLeastSquares(R1_Col_I_D& pred, int lim=1000, Real crit=0.0001) : criterion(crit), Pred(pred), Lim(lim) {} void Fit(const ColumnVector&, ColumnVector&); Real ResidualVariance() const { return errorvar; } void GetResiduals(ColumnVector& Z) const { Z = Y; } void GetStandardErrors(ColumnVector&); void GetCorrelations(SymmetricMatrix&); void GetHatDiagonal(DiagonalMatrix&) const; private: void MakeCovariance(); }; // The next class is the prototype class for calculating the // log-likelihood. // I assume first derivatives are available and something like the // Fisher Information or variance/covariance matrix of the first // derivatives or minus the matrix of second derivatives is // available. This matrix must be positive definite. class LL_D_FI { protected: ColumnVector para; // current parameter values bool wg; // true if FI matrix wanted public: virtual void Set(const ColumnVector& X) { para = X; } // set parameter values virtual void WG(bool wgx) { wg = wgx; } // set wg virtual bool IsValid() { return true; } // return true is para is OK bool IsValid(const ColumnVector& X, bool wgx=true) { Set(X); WG(wgx); return IsValid(); } virtual Real LogLikelihood() = 0; // return the loglikelihhod Real LogLikelihood(const ColumnVector& X, bool wgx=true) { Set(X); WG(wgx); return LogLikelihood(); } virtual ReturnMatrix Derivatives() = 0; // column vector of derivatives virtual ReturnMatrix FI() = 0; // Fisher Information matrix virtual ~LL_D_FI() {} // to keep gnu happy }; // This is the class for doing the maximum likelihood estimation class MLE_D_FI : public FindMaximum2 { // these replace the corresponding functions in FindMaximum2 void Value(const ColumnVector&, bool, Real&, bool&); bool NextPoint(ColumnVector&, Real&); Real LastDerivative(const ColumnVector&); // the things we need for the analysis LL_D_FI& LL; // reference to log-likelihood int Lim; // maximum number of iterations Real Criterion; // convergence criterion ColumnVector Derivs; // for the derivatives LowerTriangularMatrix LT; // Cholesky decomposition of FI SymmetricMatrix Covariance; DiagonalMatrix SE; public: MLE_D_FI(LL_D_FI& ll, int lim=1000, Real criterion=0.0001) : LL(ll), Lim(lim), Criterion(criterion) {} void Fit(ColumnVector& Parameters); void GetStandardErrors(ColumnVector&); void GetCorrelations(SymmetricMatrix&); private: void MakeCovariance(); }; #ifdef use_namespace } #endif #endif // body file: newmatnl.cpp newmat-1.10.4/newmatrc.h0000644001161000116100000001604207364443714013304 0ustar rzrrzr//$$ newmatrc.h definition file for row/column classes // Copyright (C) 1991,2,3,4,7: R B Davies #ifndef NEWMATRC_LIB #define NEWMATRC_LIB 0 #ifdef use_namespace namespace NEWMAT { #endif #include "controlw.h" /************** classes MatrixRowCol, MatrixRow, MatrixCol *****************/ // Used for accessing the rows and columns of matrices // All matrix classes must provide routines for calculating matrix rows and // columns. Assume rows can be found very efficiently. enum LSF { LoadOnEntry=1,StoreOnExit=2,DirectPart=4,StoreHere=8,HaveStore=16 }; class LoadAndStoreFlag : public ControlWord { public: LoadAndStoreFlag() {} LoadAndStoreFlag(int i) : ControlWord(i) {} LoadAndStoreFlag(LSF lsf) : ControlWord(lsf) {} LoadAndStoreFlag(const ControlWord& cwx) : ControlWord(cwx) {} }; class MatrixRowCol // the row or column of a matrix { public: // these are public to avoid // numerous friend statements int length; // row or column length int skip; // initial number of zeros int storage; // number of stored elements int rowcol; // row or column number GeneralMatrix* gm; // pointer to parent matrix Real* data; // pointer to local storage LoadAndStoreFlag cw; // Load? Store? Is a Copy? void IncrMat() { rowcol++; data += storage; } // used by NextRow void IncrDiag() { rowcol++; skip++; data++; } void IncrId() { rowcol++; skip++; } void IncrUT() { rowcol++; data += storage; storage--; skip++; } void IncrLT() { rowcol++; data += storage; storage++; } public: void Zero(); // set elements to zero void Add(const MatrixRowCol&); // add a row/col void AddScaled(const MatrixRowCol&, Real); // add a multiple of a row/col void Add(const MatrixRowCol&, const MatrixRowCol&); // add two rows/cols void Add(const MatrixRowCol&, Real); // add a row/col void NegAdd(const MatrixRowCol&, Real); // Real - a row/col void Sub(const MatrixRowCol&); // subtract a row/col void Sub(const MatrixRowCol&, const MatrixRowCol&); // sub a row/col from another void RevSub(const MatrixRowCol&); // subtract from a row/col void ConCat(const MatrixRowCol&, const MatrixRowCol&); // concatenate two row/cols void Multiply(const MatrixRowCol&); // multiply a row/col void Multiply(const MatrixRowCol&, const MatrixRowCol&); // multiply two row/cols void KP(const MatrixRowCol&, const MatrixRowCol&); // Kronecker Product two row/cols void Copy(const MatrixRowCol&); // copy a row/col void CopyCheck(const MatrixRowCol&); // ... check for data loss void Check(const MatrixRowCol&); // just check for data loss void Check(); // check full row/col present void Copy(const Real*&); // copy from an array void Copy(Real); // copy from constant void Add(Real); // add a constant void Multiply(Real); // multiply by constant Real SumAbsoluteValue(); // sum of absolute values Real MaximumAbsoluteValue1(Real r, int& i); // maximum of absolute values Real MinimumAbsoluteValue1(Real r, int& i); // minimum of absolute values Real Maximum1(Real r, int& i); // maximum Real Minimum1(Real r, int& i); // minimum Real Sum(); // sum of values void Inject(const MatrixRowCol&); // copy stored els of a row/col void Negate(const MatrixRowCol&); // change sign of a row/col void Multiply(const MatrixRowCol&, Real); // scale a row/col friend Real DotProd(const MatrixRowCol&, const MatrixRowCol&); // sum of pairwise product Real* Data() { return data; } int Skip() { return skip; } // number of elements skipped int Storage() { return storage; } // number of elements stored int Length() { return length; } // length of row or column void Skip(int i) { skip=i; } void Storage(int i) { storage=i; } void Length(int i) { length=i; } void SubRowCol(MatrixRowCol&, int, int) const; // get part of a row or column MatrixRowCol() {} // to stop warning messages ~MatrixRowCol(); FREE_CHECK(MatrixRowCol) }; class MatrixRow : public MatrixRowCol { public: // bodies for these are inline at the end of this .h file MatrixRow(GeneralMatrix*, LoadAndStoreFlag, int=0); // extract a row ~MatrixRow(); void Next(); // get next row FREE_CHECK(MatrixRow) }; class MatrixCol : public MatrixRowCol { public: // bodies for these are inline at the end of this .h file MatrixCol(GeneralMatrix*, LoadAndStoreFlag, int=0); // extract a col MatrixCol(GeneralMatrix*, Real*, LoadAndStoreFlag, int=0); // store/retrieve a col ~MatrixCol(); void Next(); // get next row FREE_CHECK(MatrixCol) }; // MatrixColX is an alternative to MatrixCol where the complete // column is stored externally class MatrixColX : public MatrixRowCol { public: // bodies for these are inline at the end of this .h file MatrixColX(GeneralMatrix*, Real*, LoadAndStoreFlag, int=0); // store/retrieve a col ~MatrixColX(); void Next(); // get next row Real* store; // pointer to local storage // less skip FREE_CHECK(MatrixColX) }; /**************************** inline bodies ****************************/ inline MatrixRow::MatrixRow(GeneralMatrix* gmx, LoadAndStoreFlag cwx, int row) { gm=gmx; cw=cwx; rowcol=row; gm->GetRow(*this); } inline void MatrixRow::Next() { gm->NextRow(*this); } inline MatrixCol::MatrixCol(GeneralMatrix* gmx, LoadAndStoreFlag cwx, int col) { gm=gmx; cw=cwx; rowcol=col; gm->GetCol(*this); } inline MatrixCol::MatrixCol(GeneralMatrix* gmx, Real* r, LoadAndStoreFlag cwx, int col) { gm=gmx; data=r; cw=cwx+StoreHere; rowcol=col; gm->GetCol(*this); } inline MatrixColX::MatrixColX(GeneralMatrix* gmx, Real* r, LoadAndStoreFlag cwx, int col) { gm=gmx; store=data=r; cw=cwx+StoreHere; rowcol=col; gm->GetCol(*this); } inline void MatrixCol::Next() { gm->NextCol(*this); } inline void MatrixColX::Next() { gm->NextCol(*this); } #ifdef use_namespace } #endif #endif newmat-1.10.4/newmatrm.cpp0000644001161000116100000001073307414432002013632 0ustar rzrrzr//$$newmatrm.cpp rectangular matrix operations // Copyright (C) 1991,2,3,4: R B Davies #include "newmat.h" #include "newmatrm.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,12); ++ExeCount; } #else #define REPORT {} #endif // operations on rectangular matrices void RectMatrixRow::Reset (const Matrix& M, int row, int skip, int length) { REPORT RectMatrixRowCol::Reset ( M.Store()+row*M.Ncols()+skip, length, 1, M.Ncols() ); } void RectMatrixRow::Reset (const Matrix& M, int row) { REPORT RectMatrixRowCol::Reset( M.Store()+row*M.Ncols(), M.Ncols(), 1, M.Ncols() ); } void RectMatrixCol::Reset (const Matrix& M, int skip, int col, int length) { REPORT RectMatrixRowCol::Reset ( M.Store()+col+skip*M.Ncols(), length, M.Ncols(), 1 ); } void RectMatrixCol::Reset (const Matrix& M, int col) { REPORT RectMatrixRowCol::Reset( M.Store()+col, M.Nrows(), M.Ncols(), 1 ); } Real RectMatrixRowCol::SumSquare() const { REPORT long_Real sum = 0.0; int i = n; Real* s = store; int d = spacing; // while (i--) { sum += (long_Real)*s * *s; s += d; } if (i) for(;;) { sum += (long_Real)*s * *s; if (!(--i)) break; s += d; } return (Real)sum; } Real RectMatrixRowCol::operator*(const RectMatrixRowCol& rmrc) const { REPORT long_Real sum = 0.0; int i = n; Real* s = store; int d = spacing; Real* s1 = rmrc.store; int d1 = rmrc.spacing; if (i!=rmrc.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in *")); } // while (i--) { sum += (long_Real)*s * *s1; s += d; s1 += d1; } if (i) for(;;) { sum += (long_Real)*s * *s1; if (!(--i)) break; s += d; s1 += d1; } return (Real)sum; } void RectMatrixRowCol::AddScaled(const RectMatrixRowCol& rmrc, Real r) { REPORT int i = n; Real* s = store; int d = spacing; Real* s1 = rmrc.store; int d1 = rmrc.spacing; if (i!=rmrc.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in AddScaled")); } // while (i--) { *s += *s1 * r; s += d; s1 += d1; } if (i) for (;;) { *s += *s1 * r; if (!(--i)) break; s += d; s1 += d1; } } void RectMatrixRowCol::Divide(const RectMatrixRowCol& rmrc, Real r) { REPORT int i = n; Real* s = store; int d = spacing; Real* s1 = rmrc.store; int d1 = rmrc.spacing; if (i!=rmrc.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in Divide")); } // while (i--) { *s = *s1 / r; s += d; s1 += d1; } if (i) for (;;) { *s = *s1 / r; if (!(--i)) break; s += d; s1 += d1; } } void RectMatrixRowCol::Divide(Real r) { REPORT int i = n; Real* s = store; int d = spacing; // while (i--) { *s /= r; s += d; } if (i) for (;;) { *s /= r; if (!(--i)) break; s += d; } } void RectMatrixRowCol::Negate() { REPORT int i = n; Real* s = store; int d = spacing; // while (i--) { *s = - *s; s += d; } if (i) for (;;) { *s = - *s; if (!(--i)) break; s += d; } } void RectMatrixRowCol::Zero() { REPORT int i = n; Real* s = store; int d = spacing; // while (i--) { *s = 0.0; s += d; } if (i) for (;;) { *s = 0.0; if (!(--i)) break; s += d; } } void ComplexScale(RectMatrixCol& U, RectMatrixCol& V, Real x, Real y) { REPORT int n = U.n; if (n != V.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in ComplexScale")); } Real* u = U.store; Real* v = V.store; int su = U.spacing; int sv = V.spacing; //while (n--) //{ // Real z = *u * x - *v * y; *v = *u * y + *v * x; *u = z; // u += su; v += sv; //} if (n) for (;;) { Real z = *u * x - *v * y; *v = *u * y + *v * x; *u = z; if (!(--n)) break; u += su; v += sv; } } void Rotate(RectMatrixCol& U, RectMatrixCol& V, Real tau, Real s) { REPORT // (U, V) = (U, V) * (c, s) where tau = s/(1+c), c^2 + s^2 = 1 int n = U.n; if (n != V.n) { Tracer tr("newmatrm"); Throw(InternalException("Dimensions differ in Rotate")); } Real* u = U.store; Real* v = V.store; int su = U.spacing; int sv = V.spacing; //while (n--) //{ // Real zu = *u; Real zv = *v; // *u -= s * (zv + zu * tau); *v += s * (zu - zv * tau); // u += su; v += sv; //} if (n) for(;;) { Real zu = *u; Real zv = *v; *u -= s * (zv + zu * tau); *v += s * (zu - zv * tau); if (!(--n)) break; u += su; v += sv; } } #ifdef use_namespace } #endif newmat-1.10.4/newmatrm.h0000644001161000116100000000754207314306134013310 0ustar rzrrzr//$$newmatrm.h rectangular matrix operations // Copyright (C) 1991,2,3,4: R B Davies #ifndef NEWMATRM_LIB #define NEWMATRM_LIB 0 #ifdef use_namespace namespace NEWMAT { #endif // operations on rectangular matrices class RectMatrixCol; class RectMatrixRowCol // a class for accessing rows and columns of rectangular matrices { protected: #ifdef use_namespace // to make namespace work public: #endif Real* store; // pointer to storage int n; // number of elements int spacing; // space between elements int shift; // space between cols or rows RectMatrixRowCol(Real* st, int nx, int sp, int sh) : store(st), n(nx), spacing(sp), shift(sh) {} void Reset(Real* st, int nx, int sp, int sh) { store=st; n=nx; spacing=sp; shift=sh; } public: Real operator*(const RectMatrixRowCol&) const; // dot product void AddScaled(const RectMatrixRowCol&, Real); // add scaled void Divide(const RectMatrixRowCol&, Real); // scaling void Divide(Real); // scaling void Negate(); // change sign void Zero(); // zero row col Real& operator[](int i) { return *(store+i*spacing); } // element Real SumSquare() const; // sum of squares Real& First() { return *store; } // get first element void DownDiag() { store += (shift+spacing); n--; } void UpDiag() { store -= (shift+spacing); n++; } friend void ComplexScale(RectMatrixCol&, RectMatrixCol&, Real, Real); friend void Rotate(RectMatrixCol&, RectMatrixCol&, Real, Real); FREE_CHECK(RectMatrixRowCol) }; class RectMatrixRow : public RectMatrixRowCol { public: RectMatrixRow(const Matrix&, int, int, int); RectMatrixRow(const Matrix&, int); void Reset(const Matrix&, int, int, int); void Reset(const Matrix&, int); Real& operator[](int i) { return *(store+i); } void Down() { store += shift; } void Right() { store++; n--; } void Up() { store -= shift; } void Left() { store--; n++; } FREE_CHECK(RectMatrixRow) }; class RectMatrixCol : public RectMatrixRowCol { public: RectMatrixCol(const Matrix&, int, int, int); RectMatrixCol(const Matrix&, int); void Reset(const Matrix&, int, int, int); void Reset(const Matrix&, int); void Down() { store += spacing; n--; } void Right() { store++; } void Up() { store -= spacing; n++; } void Left() { store--; } friend void ComplexScale(RectMatrixCol&, RectMatrixCol&, Real, Real); friend void Rotate(RectMatrixCol&, RectMatrixCol&, Real, Real); FREE_CHECK(RectMatrixCol) }; class RectMatrixDiag : public RectMatrixRowCol { public: RectMatrixDiag(const DiagonalMatrix& D) : RectMatrixRowCol(D.Store(), D.Nrows(), 1, 1) {} Real& operator[](int i) { return *(store+i); } void DownDiag() { store++; n--; } void UpDiag() { store--; n++; } FREE_CHECK(RectMatrixDiag) }; inline RectMatrixRow::RectMatrixRow (const Matrix& M, int row, int skip, int length) : RectMatrixRowCol( M.Store()+row*M.Ncols()+skip, length, 1, M.Ncols() ) {} inline RectMatrixRow::RectMatrixRow (const Matrix& M, int row) : RectMatrixRowCol( M.Store()+row*M.Ncols(), M.Ncols(), 1, M.Ncols() ) {} inline RectMatrixCol::RectMatrixCol (const Matrix& M, int skip, int col, int length) : RectMatrixRowCol( M.Store()+col+skip*M.Ncols(), length, M.Ncols(), 1 ) {} inline RectMatrixCol::RectMatrixCol (const Matrix& M, int col) : RectMatrixRowCol( M.Store()+col, M.Nrows(), M.Ncols(), 1 ) {} inline Real square(Real x) { return x*x; } inline Real sign(Real x, Real y) { return (y>=0) ? x : -x; } // assume x >=0 #ifdef use_namespace } #endif #endif // body file: newmatrm.cpp newmat-1.10.4/nl_ex.cpp0000644001161000116100000000567407330263612013123 0ustar rzrrzr// This is an example of a non-linear least squares fit. The example // is from "Nonlinear estimation" by Gavin Ross (Springer,1990), p 63. // There are better ways of doing the fit in this case so this // example is just an example. // The model is E(y) = a + b exp(-kx) and there are 6 data points. #define WANT_STREAM #define WANT_MATH #include "newmatnl.h" #include "newmatio.h" #ifdef use_namespace using namespace RBD_LIBRARIES; #endif // first define the class describing the predictor function class Model_3pe : public R1_Col_I_D { ColumnVector x_values; // the values of "x" RowVector deriv; // values of derivatives public: Model_3pe(const ColumnVector& X_Values) : x_values(X_Values) { deriv.ReSize(3); } // load X data Real operator()(int); bool IsValid() { return para(3)>0; } // require "k" > 0 ReturnMatrix Derivatives() { return deriv; } }; Real Model_3pe::operator()(int i) { Real a = para(1); Real b = para(2); Real k = para(3); Real xvi = x_values(i); Real e = exp(-k * xvi); deriv(1) = 1.0; // calculate derivatives deriv(2) = e; deriv(3) = - b * e * xvi; return a + b * e; // function value } int main() { { // Get the data ColumnVector X(6); ColumnVector Y(6); X << 1 << 2 << 3 << 4 << 6 << 8; Y << 3.2 << 7.9 << 11.1 << 14.5 << 16.7 << 18.3; // Do the fit Model_3pe model(X); // the model object NonLinearLeastSquares NLLS(model); // the non-linear least squares // object ColumnVector Para(3); // for the parameters Para << 9 << -6 << .5; // trial values of parameters cout << "Fitting parameters\n"; NLLS.Fit(Y,Para); // do the fit // Inspect the results ColumnVector SE; // for the standard errors NLLS.GetStandardErrors(SE); cout << "\n\nEstimates and standard errors\n" << setw(10) << setprecision(2) << (Para | SE) << endl; Real ResidualSD = sqrt(NLLS.ResidualVariance()); cout << "\nResidual s.d. = " << setw(10) << setprecision(2) << ResidualSD << endl; SymmetricMatrix Correlations; NLLS.GetCorrelations(Correlations); cout << "\nCorrelationMatrix\n" << setw(10) << setprecision(2) << Correlations << endl; ColumnVector Residuals; NLLS.GetResiduals(Residuals); DiagonalMatrix Hat; NLLS.GetHatDiagonal(Hat); cout << "\nX, Y, Residual, Hat\n" << setw(10) << setprecision(2) << (X | Y | Residuals | Hat.AsColumn()) << endl; // recover var/cov matrix SymmetricMatrix D; D << SE.AsDiagonal() * Correlations * SE.AsDiagonal(); cout << "\nVar/cov\n" << setw(14) << setprecision(4) << D << endl; } #ifdef DO_FREE_CHECK FreeCheck::Status(); #endif return 0; } newmat-1.10.4/nl_ex.txt0000644001161000116100000000213307215546542013153 0ustar rzrrzrFitting parameters 70.02918529 209.6252324 0.1541078372 94.78295699 49.23360397 147.1803571 0.1734849298 1.848950128 0.7422941575 1.70673579 0.1733822274 0.2113527145 0.1955923541 0.06041118379 0.1754552928 0.1754553498 0.1754553471 2.341694142e-08 0.1754553393 Converged Estimates and standard errors 19.77 0.73 -23.63 0.82 0.35 0.04 Residual s.d. = 0.42 CorrelationMatrix 1.00 -0.05 -0.91 -0.05 1.00 -0.31 -0.91 -0.31 1.00 X, Y, Residual, Hat 1.00 3.20 0.10 0.89 2.00 7.90 -0.11 0.33 3.00 11.10 -0.38 0.39 4.00 14.50 0.58 0.35 6.00 16.70 -0.16 0.32 8.00 18.30 -0.02 0.73 Var/cov 0.5295 -0.0324 -0.0250 -0.0324 0.6668 -0.0096 -0.0250 -0.0096 0.0014 newmat-1.10.4/nm10.htm0000644001161000116100000052463710416163373012606 0ustar rzrrzr Newmat10 documentation

Documentation for newmat10D, a matrix library in C++

next - skip - up - start
return to online documentation page

Copyright (C) 2006: R B Davies

2 April, 2006

1. Introduction
2. Getting started
3. Reference manual
4. Error messages
5. Design of the library

This is the how to use documentation for newmat plus some background information on its design.

There is additional support material on my web site.

Navigation:  This page is arranged in sections, sub-sections and sub-sub-sections; four cross-references are given at the top of these. Next takes you through the sections, sub-sections and sub-sub-sections in order. Skip goes to the next section, sub-section or sub-sub-section at the same level in the hierarchy as the section, sub-section or sub-sub-section that you are currently reading. Up takes you up one level in the hierarchy and start gets you back here.

Please read the sections on customising and compilers before attempting to compile newmat.

1. Introduction

next - skip - up - start

1.1 Conditions of use
1.2 Description
1.3 Is this the library for you?
1.4 Other matrix libraries
1.5 Where to find this library
1.6 How to contact the author
1.7 Change history
1.8 References

1.1 Conditions of use

next - skip - up - start


I place no restrictions on the use of newmat except that I take no liability for any problems that may arise from its use, distribution or other dealings with it.

You can use it in your commercial projects.

You can make and distribute modified or merged versions. You can include parts of it in your own software.

If you distribute modified or merged versions, please make it clear which parts are mine and which parts are modified.

For a substantially modified version, simply note that it is, in part, derived from my software. A comment in the code will be sufficient.

The software is provided "as is", without warranty of any kind.

Please understand that there may still be bugs and errors. Use at your own risk. I (Robert Davies) take no responsibility for any errors or omissions in this package or for any misfortune that may befall you or others as a result of your use, distribution or other dealings with it.


Please report bugs to me at robert (at) statsresearch.co.nz

When reporting a bug please tell me which C++ compiler you are using, and what version. Also give me details of your computer. And tell me which version of newmat (e.g. newmat03 or newmat04) you are using. Note any changes you have made to my code. If at all possible give me a piece of code illustrating the bug. See the problem report form.

Please do report bugs to me.

1.2 General description

next - skip - up - start

The package is intended for scientists and engineers who need to manipulate a variety of types of matrices using standard matrix operations. Emphasis is on the kind of operations needed in statistical calculations such as least squares, linear equation solve and eigenvalues.

It supports matrix types

Matrix rectangular matrix
nricMatrix for use with Numerical Recipes in C programs
UpperTriangularMatrix  
LowerTriangularMatrix  
DiagonalMatrix  
SymmetricMatrix  
BandMatrix  
UpperBandMatrix upper triangular band matrix
LowerBandMatrix lower triangular band matrix
SymmetricBandMatrix  
RowVector derived from Matrix
ColumnVector derived from Matrix
IdentityMatrix diagonal matrix, elements have same value

Only one element type (float or double) is supported.

The package includes the operations *, +, -, Kronecker product, Schur product, concatenation, inverse, transpose, conversion between types, submatrix, determinant, Cholesky decomposition, QR triangularisation, singular value decomposition, eigenvalues of a symmetric matrix, sorting, fast Fourier transform, printing and an interface with Numerical Recipes in C.

It is intended for matrices in the range 10 x 10 to the maximum size your machine will accommodate in a single array. The number of elements in an array cannot exceed the maximum size of an int. The package will work for very small matrices but becomes rather inefficient. Some of the factorisation functions are not (yet) optimised for paged memory and so become inefficient when used with very large matrices.

A lazy evaluation approach to evaluating matrix expressions is used to improve efficiency and reduce the use of temporary storage.

I have tested versions of the package on variety of compilers and platforms including Borland, Gnu, Microsoft, Sun and Watcom. For more details see the section on compilers.

1.3 Is this the library for you?

next - skip - up - start

Do you

  • understand * to mean matrix multiply and not element by element multiply
  • need matrix operators such as * and + defined as operators so you can write things like X = A * (B + C);
  • need a variety of types of matrices (but not sparse)
  • need only one element type (float or double)
  • work with matrices in the range 10 x 10 up to what can be stored in memory
  • tolerate a moderately large but not huge package
  • need high quality but not necessarily the latest numerical methods.

Then newmat may be the right matrix library for you.

1.4 Other matrix libraries

next - skip - up - start

For details of other C++ matrix libraries look at http://www.robertnz.net/cpp_site.html. Look at the section lists of libraries which gives the locations of several very comprehensive lists of matrix and other C++ libraries and at the section source code.

1.5 Where to find this library

next - skip - up - start

1.6 How to contact the author

next - skip - up - start

   Robert Davies
   16 Gloucester Street
   Wilton
   Wellington
   New Zealand

   email: robert at statsresearch.co.nz

1.7 Change history

next - skip - up - start

Newmat10D - April, 2006:

Compatibility fix for Gnu G++ 4.1.

Newmat10C - March, 2006:

Update conditions of use to be acceptable for Debian distribution, a few minor fixes; additional make files; update include.h, myexpect.h, myexcept.cpp, precisio.h.

Newmat10B - January, 2005:

Fix compatibility problems with Gnu G++ 3.4 and Intel 8.1 compilers; update include.h, myexpect.h, myexcept.cpp, precisio.h.

Newmat10A - October, 2002:

Fix error in Kronecker product; fixes for Intel and GCC3 compilers.

Newmat10 - January, 2002:

Improve compatibility with GCC, fix errors in FFT and GenericMatrix, update simulated exceptions, maxima, minima, determinant, dot product and Frobenius norm functions, update make files for CC and GCC, faster FFT, A.ReSize(B), fix pointer arithmetic, << for loading data into rows, IdentityMatrix, Kronecker product, sort singular values.

Newmat09 - September, 1997:

Operator ==, !=, +=, -=, *=, /=, |=, &=. Follow new rules for for (int i; ... ) construct. Change Boolean, TRUE, FALSE to bool, true, false. Change ReDimension to ReSize. SubMatrix allows zero rows and columns. Scalar +, - or * matrix is OK. Simplify simulated exceptions. Fix non-linear programs for AT&T compilers. Dummy inequality operators. Improve internal row/column operations. Improve matrix LU decomposition. Improve sort. Reverse function. IsSingular function. Fast trig transforms. Namespace definitions.

Newmat08A - July, 1995:

Fix error in SVD.

Newmat08 - January, 1995:

Corrections to improve compatibility with Gnu, Watcom. Concatenation of matrices. Elementwise products. Option to use compilers supporting exceptions. Correction to exception module to allow global declarations of matrices. Fix problem with inverse of symmetric matrices. Fix divide-by-zero problem in SVD. Include new QR routines. Sum function. Non-linear optimisation. GenericMatrices.

Newmat07 - January, 1993

Minor corrections to improve compatibility with Zortech, Microsoft and Gnu. Correction to exception module. Additional FFT functions. Some minor increases in efficiency. Submatrices can now be used on RHS of =. Option for allowing C type subscripts. Method for loading short lists of numbers.

Newmat06 - December 1992:

Added band matrices; 'real' changed to 'Real' (to avoid potential conflict in complex class); Inject doesn't check for no loss of information; fixes for AT&T C++ version 3.0; real(A) becomes A.AsScalar(); CopyToMatrix becomes AsMatrix, etc; .c() is no longer required (to be deleted in next version); option for version 2.1 or later. Suffix for include files changed to .h; BOOL changed to Boolean (BOOL doesn't work in g++ v 2.0); modifications to allow for compilers that destroy temporaries very quickly; (Gnu users - see the section of compilers). Added CleanUp, LinearEquationSolver, primitive version of exceptions.

Newmat05 - June 1992:

For private release only

Newmat04 - December 1991:

Fix problem with G++1.40, some extra documentation

Newmat03 - November 1991:

Col and Cols become Column and Columns. Added Sort, SVD, Jacobi, Eigenvalues, FFT, real conversion of 1x1 matrix, Numerical Recipes in C interface, output operations, various scalar functions. Improved return from functions. Reorganised setting options in "include.hxx".

Newmat02 - July 1991:

Version with matrix row/column operations and numerous additional functions.

Matrix - October 1990:

Early version of package.

1.8 References

next - skip - up - start

  • The matrix LU decomposition is from Golub, G.H. & Van Loan, C.F. (1996), Matrix Computations, published by Johns Hopkins University Press.
  • Part of the matrix inverse/solve routine is adapted from Press, Flannery, Teukolsky, Vetterling (1988), Numerical Recipes in C, published by the Cambridge University Press.
  • Many of the advanced matrix routines are adapted from routines in Wilkinson and Reinsch (1971), Handbook for Automatic Computation, Vol II, Linear Algebra published by Springer Verlag.
  • The fast Fourier transform is adapted from Carl de Boor (1980), Siam J Sci Stat Comput, pp173-8 and the fast trigonometric transforms from Charles Van Loan (1992) in Computational frameworks for the fast Fourier transform published by SIAM.
  • The sort function is derived from Sedgewick, Robert (1992), Algorithms in C++ published by Addison Wesley.

For references about Newmat see

  • Davies, R.B. (1994) Writing a matrix package in C++. In OON-SKI'94: The second annual object-oriented numerics conference, pp 207-213. Rogue Wave Software, Corvallis.
  • Eddelbuttel, Dirk (1996) Object-oriented econometrics: matrix programming in C++ using GCC and Newmat. Journal of Applied Econometrics, Vol 11, No 2, pp 199-209.

2. Getting started

next - skip - up - start

2.1 Overview
2.2 Make files
2.3 Customising
2.4 Compilers
2.5 Updating from previous versions
2.6 Catching exceptions
2.7 Example
2.8 Testing
2.9 Bugs
2.10 Files in newmat10
2.11 Problem report form

2.1 Overview

next - skip - up - start

I use .h as the suffix of definition files and .cpp as the suffix of C++ source files.

You will need to compile all the *.cpp files listed as program files in the files section to get the complete package. Ideally you should store the resulting object files as a library. The tmt*.cpp files are used for testing, example.cpp is an example and sl_ex.cpp, nl_ex.cpp and garch.cpp are examples of the non-linear solve and optimisation routines. A demonstration and test of the exception mechanism is in test_exc.cpp.

I include a number of make files for compiling the example and the test package. See the section on make files for details. But with the PC compilers, its pretty quick just to load all the files in the interactive environments by pointing and clicking.

Use the large or win32 console model when you are using a PC. Do not outline inline functions. You may need to increase the stack size.

Your source files that access the newmat will need to #include one or more of the following files.

include.h to access just the compiler options
newmat.h to access just the main matrix library (includes include.h)
newmatap.h to access the advanced matrix routines such as Cholesky decomposition, QR triangularisation etc (includes newmat.h)
newmatio.h to access the output routines (includes newmat.h) You can use this only with compilers that support the standard input/output routines including manipulators
newmatnl.h to access the non-linear optimisation routines (includes newmat.h)

See the section on customising to see how to edit include.h for your environment and the section on compilers for any special problems with the compiler you are using.

2.2 Make files

next - skip - up - start

I have included make files for CC, Microsoft, Intel, Borland 5.5 and Gnu compilers for compiling the examples. You can generate make files for a number of other compilers with my genmake utility. Make files provide a way of compiling your programs without using the IDE that comes with PC compilers. See the files section for details. See the example for how to use them. Leave out the target name to compile and link all my examples and test files. For more information on how to use these files see the documentation for my genmake utility.

PC

I include make files for Microsoft, Intel, Borland 5.5. For Borland you will need to edit it to show where you have stored your Borland compiler. For make files for other compilers use my genmake utility.

Unix

The make file for the Unix CC compilers link a .cxx file to each .cpp file since some of these compilers do not recognise .cpp as a legitimate extension for a C++ file. I suggest you delete this part of the make file and, if necessary, rename the .cpp files to something your compiler recognises.

My make file for Gnu GCC on Unix systems is for use with gmake rather than make. I assume your compiler recognises the .cpp extension. Ordinary make works with it on the Sun but not the Silicon Graphics or HP machines. On Linux use make.

My make file for the CC compilers works with the ordinary make.

To compile everything with the CC compiler use

   make -f nm_cc.mak

or for the gnu compiler use

   gmake -f nm_gnu.mak

There is a line in the make file for CC rm -f $*.cxx. Some systems won't accept this line and you will need to delete it. In this case, if you have a bad compile and you are using my scheme for linking .cxx files, you will need to delete the .cxx file link generated by that compile before you can do the next one.

There is also a make file for the Intel compiler for Linux.

2.3 Customising

next - skip - up - start

The file include.h sets a variety of options including several compiler dependent options. You may need to edit include.h to get the options you require. If you are using a compiler different from one I have worked with you may have to set up a new section in include.h appropriate for your compiler.

Borland, Turbo, Gnu, Microsoft and Watcom are recognised automatically. If none of these are recognised a default set of options is used. These are fine for AT&T, HPUX and Sun C++. If you using a compiler I don't know about you may have to write a new set of options.

There is an option in include.h for selecting whether you use compiler supported exceptions, simulated exceptions, or disable exceptions. I now set compiler supported exceptions as the default. Use the option for compiler supported exceptions if and only if you have set the option on your compiler to recognise exceptions. Disabling exceptions sometimes helps with compilers that are incompatible with my exception simulation scheme.

If you are using an older compiler that does not recognises bool as required by the standard then de-activate the statement #define bool_LIB. This will turn on my Boolean class.

Activate the appropriate statement to make the element type float or double.

I suggest you leave the options TEMPS_DESTROYED_QUICKLY, TEMPS_DESTROYED_QUICKLY_R de-activated, unless you are using a very old version of Gnu compiler (<2.6). This stores the trees describing matrix expressions on the stack rather than the heap. See the discussion on destruction of temporaries for more explanation.

The option DO_FREE_CHECK is used for tracking memory leaks and normally should not be activated.

Activate SETUP_C_SUBSCRIPTS if you want to use traditional C style element access. Note that this does not change the starting point for indices when you are using round brackets for accessing elements or selecting submatrices. It does enable you to use C style square brackets.

Activate #define use_namespace if you want to use namespaces. Do this only if you are sure your compiler supports namespaces. If you do turn this option on, be prepared to turn it off again if the compiler reports inaccessible variables or the linker reports missing links.

Activate #define _STANDARD_ to use the standard names for the included files and to find the floating point precision data using the floating point standard. This will work only with the most recent compilers. This is automatically turned on for the Gnu compiler version 3 and the Intel compiler for Linux.

If you haven't defined _STANDARD_ and are using a compiler that include.h does not recognise and you want to pick up the floating point precision data from float.h then activate #define use_float_h. Otherwise the floating point precision data will be accessed from values.h. You may need to do this with computers from Digital, in particular.

2.4 Compilers

next - skip - up - start

2.4.1 AT&T
2.4.2 Borland
2.4.3 Gnu G++
2.4.4 HPUX
2.4.5 Intel
2.4.6 Microsoft
2.4.7 Sun
2.4.8 Watcom

I have tested this library on a number of compilers. Here are the levels of success and any special considerations. In most cases I have chosen code that works under all the compilers I have access to, but I have had to include some specific work-arounds for some compilers. For the PC versions, I use Pentium 3 & 4 computers running windows 2000 or XP or various varieties of Linux (Red Hat or Fedora). The Unix versions are on a Sun Sparc station. Thanks to Victoria University for access to the Sparc.

I have set up a block of code for each of the compilers in include.h. Turbo, Borland, Gnu, Microsoft and Watcom are recognised automatically. There is a default option that works for AT&T, Sun C++ and HPUX. So you don't have to make any changes for these compilers. Otherwise you may have to build your own set of options in include.h.

2.4.1 AT&T

next - skip - up - start

The AT&T compiler used to be available on a wide variety of Unix workstations. I don't know if anyone still uses it. However the AT&T options are the default if your compiler is not recognised.

AT&T C++ 2.1; 3.0.1 on a Sun: Previous versions worked on these compilers, which I no longer have access to.

In AT&T 2.1 you may get an error when you use an expression for the single argument when constructing a Vector or DiagonalMatrix or one of the Triangular Matrices. You need to evaluate the expression separately.

2.4.2 Borland

next - skip - up - start

Newer compilers

Borland Builder version 6: This is not compatible with newmat10. Use newmat11 instead.

Borland Builder version 5: This works fine in console mode and no special editing of the source codes is required. I haven't tested it in GUI mode. You can set the newmat10 options to use namespace and the standard library. You should turn off the Borland option to use pre-compiled headers. There are notes on compiling with the IDE on my website. Alternatively you can use the nm_b55.mak make file.

Borland Builder version 4: I have successfully used this on older versions of newmat using the console wizard (menu item file/new - select new tab). Use compiler exceptions. Suppose you are compiling my test program tmt. Rename my main() function in tmt.cpp to my_main(). Rename tmt.cpp to tmt_main.cpp. Borland will generate a new file tmt.cpp containing their main() function. Put the line int my_main(); above this function and put return my_main(); into the body of main().

Borland compiler version 5.5: this is the free C++ compiler available from Borland's web site. I suggest you use the compiler supported exceptions and turn on standard in include.h. You can use the make file nm_b55.mak after editing to correct the file locations for your system.

Older compilers

Borland C++ 3.1, 5.02: Use the simulated exceptions with these. Then version 5.02 works OK. You will need to use the large or 32 bit flat model. If you are not debugging, turn off the options that collect debugging information. It compiles with version 3.1 but you can't run the tmt test program.

If you are using versions earlier than 5 remember to edit include.h to activate my Boolean class.

When running my test program under ms-dos you may run out of memory. Either compile the test routine to run under easywin or use simulated exceptions rather than the built in exceptions.

If you can, upgrade to windows 9X or window NT and use the 32 bit console model.

If you are using the 16 bit large model, don't forget to keep all matrices less than 64K bytes in length (90x90 for a rectangular matrix if you are using double as your element type). Otherwise your program will crash without warning or explanation. You will need to break the tmt set of test files into several parts to get the program to fit into your computer and run without stack overflow.

One version of Borland had DBL_MIN incorrectly defined. If you are using an older version of Borland and are getting strange numerical errors in the test programs reinstate the commented out statements in precision.h.

You can generate make files for versions 5 or 3.1 with my genmake utility.

2.4.3 Gnu G++

next - skip - up - start

Gnu G++ 3.3, 4.0, 4.1: These work OK. If you are using a much earlier version see if you can upgrade. Standard is automatically turned on with 3.X.

If you are using 2.6 or earlier remember to edit include.h to activate my Boolean class. In 2.6.?, fabs(*X++) causes a problem. You may need to write you own non-inlined version. 

For versions earlier than 2.6.0 you must enable the options TEMPS_DESTROYED_QUICKLY and TEMPS_DESTROYED_QUICKLY_R. You can't use expressions like Matrix(X*Y) in the middle of an expression and (Matrix)(X*Y) is unreliable. If you write a function returning a matrix, you MUST use the ReturnMatrix method described in this documentation. This is because g++ destroys temporaries occurring in an expression too soon for the two stage way of evaluating expressions that newmat uses. You will have problems with versions of Gnu earlier than 2.3.1.

2.4.4 HP-UX

next - skip - up - start

HP 9000 series HP-UX. I no longer have access to this compiler. Newmat09 worked without problems with the simulated exceptions; haven't tried the built-in exceptions.

With recent versions of the compiler you may get warning messages like Unsafe cast between pointers/references to incomplete classes. At present, I think these can be ignored.

Here are comments I made in 1997.

I have tried the library on two versions of HP-UX. (I don't know the version numbers, the older is a clone of AT&T 3, the newer is HP's version with exceptions). Both worked after the modifications described in this section.

With the older version of the compiler I needed to edit the math.h library file to remove a duplicate definition of abs.

With the newer version you can set the +eh option to enable exceptions and activate the UseExceptions option in include.h. If you are using my make file, you will need to replace CC with CC +eh where ever CC occurs. I recommend that you do not do this and either disable exceptions or use my simulated exceptions. I get core dumps when I use the built-in exceptions and suspect they are not sufficiently debugged as yet.

If you are using my simulated exceptions you may get a mass of error messages from the linker about __EH_JMPBUF_TEMP. In this case get file setjmp.h (in directory /usr/include/CC ?) and put extern in front of the line

   jmp_buf * __EH_JMPBUF_TEMP;

The file setjmp.h is accessed in my file myexcept.h. You may want to change the #include statement to access your edited copy of setjmp.h.

2.4.5 Intel

next - skip - up - start

Newmat works correctly with the Intel 9 C++ compilers for Windows and for Linux. Standard is automatically switched on for the Linux version and for the Windows version if you are emulating VC++ 7 or higher.

2.4.6 Microsoft

next - skip - up - start

Newer versions

See my web site for instructions how to work Microsoft's IDE.

Microsoft Visual C++ 8: I have tested the express version using my make file run the compiler.

Microsoft Visual C++ 7, 7.1: This works OK. Note that all my tests have been in console mode. The standard option is on by default but I am still a bit wary about the namespace option.

Microsoft Visual C++ 6: Get the latest service pack. I have tried this in console mode and it seems to work satisfactorily. Use the compiler supported exceptions. You may be able to use the namespace and standard options but I suggest not using namespace. If you want to work under MFC you may need to #include "stdafx.h" at the beginning of each .cpp file.

Microsoft Visual C++ 5: I have tried this in console mode and it seems to work satisfactorily. There may be a problem with namespace (fixed by Service Pack 3?). Turn optimisation off. Use the compiler supported exceptions. If you want to work under MFC  you may need to #include "stdafx.h" at the beginning of each .cpp file.

Older versions

Microsoft Visual C++ 2.0: This used to work OK. I haven't tried it with recent versions of newmat.

You must #define TEMPS_DESTROYED_QUICKLY owing to a bug in version 7 (at least) of MSC. There are some notes in the file include.h on changes to run under version 7. I haven't tried newmat10 on version 7.

Microsoft Visual C++ 1.51. Disable exceptions, comment out the line in include.h #define TEMPS_DESTROYED_QUICKLY_R. In tmt.cpp, comment out the Try and CatchAll lines at the beginning of main() and the line trymati(). You can use the makefile ms.mak. You will probably need to break the tmt test files into two parts to get the program to link.

If you can, upgrade to windows 95, 98 or window NT and use the 32 bit console model.

If you are using the 16 bit large model, don't forget to keep all matrices less than 64K bytes in length (90x90 for a rectangular matrix if you are using double as your element type). Otherwise your program will crash without warning or explanation. You may need to break the tmt set of test files into two parts to get the program to fit into your computer.

Microsoft Visual C++ 4: I haven't tried this - a correspondent reports: I use Microsoft Visual C++ Version 4. there is only one minor problem. In all files you must include #include "stdafx.h" (presumably if you are using MFC). This file contains essential information for VC++. Leave it out and you get Unexpected end of file.

2.4.7 Sun

next - skip - up - start

Sun C++: The current version works fine with compiler supported exceptions. Sun C++ (version 5): There seems to be a problem with exceptions. If you use my simulated exceptions the non-linear optimisation programs hang. If you use the compiler supported exceptions my tmt and test_exc programs crash. You should disable exceptions.

2.4.8 Watcom

next - skip - up - start

Open Watcom C++: this works fine.

2.5 Updating from previous versions

next - skip - up - start

Newmat10 includes new maxima, minima, determinant, dot product and Frobenius norm functions, a faster FFT, revised make files for GCC and CC compilers, several corrections, new ReSize function, IdentityMatrix and Kronecker Product. Singular values from SVD are sorted. The program files include a new file, newfft.cpp, so you will need to include this in the list of files in your IDE and make files. There is also a new test file tmtm.cpp. Pointer arithmetic now mostly meets requirements of standard. You can use << to load data into rows of a matrix. The default options in include.h have been changed. If you are updating from a beta version of newmat09 look through the next section as there were some late changes to newmat09.

If you are upgrading from newmat08 note the following:

  • Boolean, TRUE, FALSE are now bool, true, false. See customising if your compiler supports the bool class.
  • ReDimension is now ReSize.
  • The simulated exception package has been updated.
  • Operators ==, !=, +=, -=, *=, |=, &= are now supported as binary matrix operators.
  • A+=f, A-=f, A*=f, A/=f, f+A, f-A, f*A are supported for A matrix, f scalar.
  • Fast trigonometric transforms.
  • Reverse function for reversing order of elements in a vector or matrix.
  • IsSingular function.
  • An option is included for defining namespaces.
  • Dummy inequality operators are defined for compatibility with the STL.
  • The row/column classes in newmat3.cpp have been modified to improve efficiency and correct an invalid use of pointer arithmetic. Most users won't be using these classes explicitly; if you are, please contact me for details of the changes.
  • Matrix LU decomposition rewritten (faster for large arrays).
  • The sort function rewritten (faster).
  • The documentation files newmata.txt and newmatb.txt have been amalgamated and both are included in the hypertext version.
  • Some of the make files reorganised again.

If you are upgrading from newmat07 note the following:

  • .cxx files are now .cpp files. Some versions of won't accept .cpp. The make files for Gnu and AT&T link the .cpp files to .cxx files before compilation and delete the links after compilation.
  • An option in include.h allows you to use compiler supported exceptions, simulated exceptions or disable exceptions. Edit the file include.h to select one of these three options. Don't simulate exceptions if you have set your compiler's option to implement exceptions.
  • New QR decomposition functions.
  • A non-linear least squares class.
  • No need to explicitly set the AT&T option in include.h.
  • Concatenation and elementwise multiplication.
  • A new GenericMatrix class.
  • Sum function.
  • Some of the make files reorganised.

If you are upgrading from newmat06 note the following:

  • If you are using << to load a Real into a submatrix change this to =.

If you are upgrading from newmat03 or newmat04 note the following

  • .hxx files are now .h files
  • real changed to Real
  • BOOL changed to Boolean
  • CopyToMatrix changed to AsMatrix, etc
  • real(A) changed to A.AsScalar()

The current version is quite a bit longer that newmat04, so if you are almost out of space with newmat04, don't throw newmat04 away until you have checked your program will work under this version.

See the change history for other changes.

2.6 Catching exceptions

This section applies particularly to people using compiler supported exceptions rather than my simulated exceptions.

If newmat detects an error it will throw an exception. It is important that you catch this exception and print the error message. Otherwise you will get an unhelpful message like abnormal termination. I suggest you set up your main program like 

#define WANT_STREAM             // or #include <iostream>
#include "include.h"            // or #include "newmat.h"
#include "myexcept.h"

main()
{
   try
   {
      ... your program here
   }
   // catch exceptions thrown by my programs
   catch(Exception) { cout << Exception::what() << endl; }
   // catch exceptions thrown by other people's programs
   catch(...) { cout << "exception caught in main program" << endl; }
   return 0;
}

If you are using a GUI version rather a console version of the program you will need to replace the cout statements by windows pop-up messages.

If you are using my simulated exceptions or have set the disable exceptions option in include.h then uncaught exceptions automatically print the error message generated by the exception so you can ignore this section. Alternatively use Try, Catch and CatchAll in place of try, catch and catch(...) in the preceding code. It is probably a good idea to do this if you are using a GUI version of the program as opposed to a console version as the cout statement used in newmat's Terminate function may be ignored in a GUI version.

See the section on exceptions for more information on the exception structure.

2.7 Example

next - skip - up - start

An example is given in example.cpp. This gives a simple linear regression example using five different algorithms. The correct output is given in example.txt. The program carries out a rough check that no memory is left allocated on the heap when it terminates. See the section on testing for a comment on the reliability of this check (generally it doesn't work with the newer compilers) and the use of the DO_FREE_CHECK option.

I include a variety of make files. To compile the example use a command like

   gmake -f nm_gnu.mak example              (Gnu G++)
   gmake -f nm_cc.mak example               (AT&T, HPUX, Sun)
   make -f nm_b55.mak example.exe           (Borland C++ 5.5)

You can generate make make files for a number of other compilers with my genmake utility.

To compile all the example and test files use a command like

   gmake -f nm_gnu.mak                      (Gnu G++)

The example uses io manipulators. It will not work with a compiler that does not support the standard io manipulators.

Other example files are nl_ex.cpp and garch.cpp for demonstrating the non-linear fitting routines, sl_ex for demonstrating the solve function and test_exc for demonstrating the exceptions.

2.8 Testing

next - skip - up - start

The library package contains a comprehensive test program in the form of a series of files with names of the form tmt?.cxx. The files consist of a large number of matrix formulae all of which evaluate to zero (except the first one which is used to check that we are detecting non-zero matrices). The printout should state that it has found just one non-zero matrix.

The test program should be run with Real typedefed to double rather than float in include.h.

Make sure the C subscripts are enabled if you want to test these.

If you are carrying out some form of bounds checking, for example, with Borland's CodeGuard, then disable the testing of the Numerical Recipes in C interface. Activate the statement #define DONT_DO_NRIC in tmt.h.

Various versions of the make file (extension .mak) are included with the package. See the section on make files.

The program also allocates and deletes a large block and small block of memory before it starts the main testing and then at the end of the test. It then checks that the blocks of memory were allocated in the same place. If not, then one suspects that there has been a memory leak. i.e. a piece of memory has been allocated and not deleted.

This is not completely foolproof. Programs may allocate extra print buffers while the program is running. I have tried to overcome this by doing a print before I allocate the first memory block. Programs may allocate memory for different sized items in different places, or might not allocate items consecutively. Or they might mix the items with memory blocks from other programs. Nevertheless, I seem to get consistent answers from some of the compilers I work with, so I think this is a worthwhile test. The compilers that the test seems to work for include the Borland compilers, Microsoft VC++ 6 , Watcom 10a, and Gnu 2.96 for Linux.

If the DO_FREE_CHECK option in include.h is activated, the program checks that each new is balanced with exactly one delete. This provides a more definitive test of no memory leaks. There are additional statements in myexcept.cpp which can be activated to print out details of the memory being allocated and released.

I have included a facility for checking that each piece of code in the library is really exercised by the test routines. Each block of code in the main part of the library contains a word REPORT. newmat.h has a line defining REPORT that can be activated (deactivate the dummy version). This gives a printout of the number of times each of the REPORT statements in the .cpp files is accessed. Use a grep with line numbers to locate the lines on which REPORT occurs and compare these with the lines that the printout shows were actually accessed. One can then see which lines of code were not accessed.

2.9 Bugs

next - skip - up - start

  • Small memory leaks may occur when an exception is thrown and caught.
  • My exception scheme may not be not properly linked in with the standard library exceptions. In particular, my scheme may fail to catch out-of-memory exceptions.

2.10 List of files

next - skip - up - start

Documentation README(.txt) readme file
  COPYING.(.txt) permission to copy, modify etc
  AUTHORS(.txt) author details
  nm10.htm documentation file
  add_time.pgn image used by nm10.htm - move to subdirectory "images"
  rbd.css style sheet for nm10.htm
Definition files boolean.h boolean class definition
  controlw.h control word definition file
  include.h details of include files and options
  myexcept.h general exception handler definitions
  newmat.h main matrix class definition file
  newmatap.h applications definition file
  newmatio.h input/output definition file
  newmatnl.h non-linear optimisation definition file
  newmatrc.h row/column functions definition files
  newmatrm.h rectangular matrix access definition files
  precisio.h numerical precision constants
  solution.h one dimensional solve definition file
Program files bandmat.cpp band matrix routines
  cholesky.cpp Cholesky decomposition
  evalue.cpp eigenvalues and eigenvector calculation
  fft.cpp fast Fourier, trig. transforms
  hholder.cpp QR routines
  jacobi.cpp eigenvalues by the Jacobi method
  myexcept.cpp general error and exception handler
  newfft.cpp new fast Fourier transform
  newmat1.cpp type manipulation routines
  newmat2.cpp row and column manipulation functions
  newmat3.cpp row and column access functions
  newmat4.cpp constructors, resize, utilities
  newmat5.cpp transpose, evaluate, matrix functions
  newmat6.cpp operators, element access
  newmat7.cpp invert, solve, binary operations
  newmat8.cpp LU decomposition, scalar functions
  newmat9.cpp output routines
  newmatex.cpp matrix exception handler
  newmatnl.cpp non-linear optimisation
  newmatrm.cpp rectangular matrix access functions
  sort.cpp sorting functions
  solution.cpp one dimensional solve
  submat.cpp submatrix functions
  svd.cpp singular value decomposition
Example files example.cpp example of use of package
  example.txt output from example
  sl_ex.cpp example of OneDimSolve routine
  sl_ex.txt output from example
  nl_ex.cpp example of non-linear least squares
  nl_ex.txt output from example
  garch.cpp example of maximum-likelihood fit
  garch.dat data file for garch.cpp
  garch.txt output from example
  test_exc.cpp demonstration exceptions
  test_exc.txt output from test_exc.cpp
Test files tmt.h header file for test files
  tmt*.cpp test files (see the section on testing)
  tmt.txt output from test files
Make files nm_gnu.mak make file for Gnu G++
  nm_cc.mak make file for AT&T, Sun and HPUX
  nm_b55.mak make file for Borland C++ 5.5
  nm_m6.mak make file for Microsoft Visual C++ 6, 7, 7.1
  nm_m8.mak make file for Microsoft Visual C++ 8
  nm_i8.mak make file for Intel C++ 8,9 for Windows
  nm_il8.mak make file for Intel C++ 8,9 for Linux
  nm_ow.mak make file for Open Watcom
  newmat.lfl library file list for use with genmake
  nm_targ.txt target file list for use with genmake

2.11 Problem report form

next - skip - up - start

Copy and paste this to your editor; fill it out and email to robert  at  statsresearch.co.nz

But first look in my web page http://www.robertnz.net/bugs.htm to see if the bug has already been reported.

 Version: ............... newmat10D (2 April 2006)
 Your email address: ....
 Today's date: ..........
 Your machine: ..........
 Operating system: ......
 Compiler & version: ....
 Compiler options
   (eg GUI or console)...
 Describe the problem - attach examples if possible:





-----------------------------------------------------------

3. Reference manual

next - skip - up - start

3.1 Constructors
3.2 Accessing elements
3.3 Assignment and copying
3.4 Entering values
3.5 Unary operations
3.6 Binary operations
3.7 Matrix and scalar ops
3.8 Scalar functions - size & shape
3.9 Scalar functions - maximum & minimum
3.10 Scalar functions - numerical
3.11 Submatrices
3.12 Change dimension
3.13 Change type
3.14 Multiple matrix solve
3.15 Memory management
3.16 Efficiency
3.17 Output
3.18 Accessing unspecified type
3.19 Cholesky decomposition
3.20 QR decomposition
3.21 Singular value decomposition
3.22 Eigenvalue decomposition
3.23 Sorting
3.24 Fast Fourier transform
3.25 Fast trigonometric transforms
3.26 Numerical recipes in C
3.27 Exceptions
3.28 Cleanup following exception
3.29 Non-linear applications
3.30 Standard template library
3.31 Namespace

3.1 Constructors

next - skip - up - start

To construct an m x n matrix, A, (m and n are integers) use

    Matrix A(m,n);

The UpperTriangularMatrix, LowerTriangularMatrix, SymmetricMatrix and DiagonalMatrix types are square. To construct an n x n matrix use, for example

    UpperTriangularMatrix UT(n);
    LowerTriangularMatrix LT(n);
    SymmetricMatrix S(n);
    DiagonalMatrix D(n);

Band matrices need to include bandwidth information in their constructors.

    BandMatrix BM(n, lower, upper);
    UpperBandMatrix UB(n, upper);
    LowerBandMatrix LB(n, lower);
    SymmetricBandMatrix SB(n, lower);

The integers upper and lower are the number of non-zero diagonals above and below the diagonal (excluding the diagonal) respectively.

The RowVector and ColumnVector types take just one argument in their constructors:

    RowVector RV(n);
    ColumnVector CV(n);

These constructors do not initialise the elements of the matrices. To set all the elements to zero use, for example,

    Matrix A(m, n); A = 0.0;

The IdentityMatrix takes one argument in its constructor specifying its dimension.

    IdentityMatrix I(n);

The value of the diagonal elements is set to 1 by default, but you can change this value as with other matrix types.

You can also construct vectors and matrices without specifying the dimension. For example

    Matrix A;

In this case the dimension must be set by an assignment statement or a re-size statement.

You can also use a constructor to set a matrix equal to another matrix or matrix expression.

    Matrix A = UT;
    Matrix A = UT * LT;

Only conversions that don't lose information are supported - eg you cannot convert an upper triangular matrix into a diagonal matrix using =.

3.2 Accessing elements

next - skip - up - start

Elements are accessed by expressions of the form A(i,j) where i and j run from 1 to the appropriate dimension. Access elements of vectors with just one argument. Diagonal matrices can accept one or two subscripts.

This is different from the earliest version of the package in which the subscripts ran from 0 to one less than the appropriate dimension. Use A.element(i,j) if you want this earlier convention.

A(i,j) and A.element(i,j) can appear on either side of an = sign.

If you activate the #define SETUP_C_SUBSCRIPTS in include.h you can also access elements using the traditional C style notation. That is A[i][j] for matrices (except diagonal) and V[i] for vectors and diagonal matrices. The subscripts start at zero (i.e. like element) and there is no range checking. Because of the possibility of confusing V(i) and V[i], I suggest you do not activate this option unless you really want to use it.

Symmetric matrices are stored as lower triangular matrices. It is important to remember this if you are using the A[i][j] method of accessing elements. Make sure the first subscript is greater than or equal to the second subscript. However, if you are using the A(i,j) method the program will swap i and j if necessary; so it doesn't matter if you think of the storage as being in the upper triangle (but it does matter in some other situations such as when entering data).

The IdentityMatrix type does not support element access.

3.3 Assignment and copying

next - skip - up - start

The operator = is used for copying matrices, converting matrices, or evaluating expressions. For example

    A = B;  A = L;  A = L * U;

Only conversions that don't lose information are supported. The dimensions of the matrix on the left hand side are adjusted to those of the matrix or expression on the right hand side. Elements on the right hand side which are not present on the left hand side are set to zero.

The operator << can be used in place of = where it is permissible for information to be lost.

For example

    SymmetricMatrix S; Matrix A;
    ......
    S << A.t() * A;

is acceptable whereas

    S = A.t() * A;                            // error

will cause a runtime error since the package does not (yet?) recognise A.t()*A as symmetric.

Note that you can not use << with constructors. For example

    SymmetricMatrix S << A.t() * A;           // error

does not work.

Also note that << cannot be used to load values from a full matrix into a band matrix, since it will be unable to determine the bandwidth of the band matrix.

A third copy routine is used in a similar role to =. Use

    A.Inject(D);

to copy the elements of D to the corresponding elements of A but leave the elements of A unchanged if there is no corresponding element of D (the = operator would set them to 0). This is useful, for example, for setting the diagonal elements of a matrix without disturbing the rest of the matrix. Unlike = and <<, Inject does not reset the dimensions of A, which must match those of D. Inject does not test for no loss of information.

You cannot replace D by a matrix expression. The effect of Inject(D) depends on the type of D. If D is an expression it might not be obvious to the user what type it would have. So I thought it best to disallow expressions.

Inject can be used for loading values from a regular matrix into a band matrix. (Don't forget to zero any elements of the left hand side that will not be set by the loading operation).

Both << and Inject can be used with submatrix expressions on the left hand side. See the section on submatrices.

To set the elements of a matrix to a scalar use operator =

    Real r; int m,n;
    ......
    Matrix A(m,n); A = r;

Notes:

  • When you do a matrix assignment to another matrix or matrix expression with either = or << the original data array associated with the matrix being assigned to is destroyed even if there is no change in length. See the section on storage. This means, in particular, that pointers to matrix elements - e.g. Real* a; a = &(A(1,1)); become invalid. If you want avoid this you can use Inject rather than =. But remember that you may need to zero the matrix first.

3.4 Entering values

next - skip - up - start

You can load the elements of a matrix from an array:

    Matrix A(3,2);
    Real a[] = { 11,12,21,22,31,33 };
    A << a;

This construction does not check that the numbers of elements match correctly. This version of << can be used with submatrices on the left hand side. It is not defined for band matrices.

Alternatively you can enter short lists using a sequence of numbers separated by << .

    Matrix A(3,2);
    A << 11 << 12
      << 21 << 22
      << 31 << 32;

This does check for the correct total number of entries, although the message for there being insufficient numbers in the list may be delayed until the end of the block or the next use of this construction. This does not work for band matrices or for long lists. It does work for submatrices if the submatrix is a single complete row. For example

    Matrix A(3,2);
    A.Row(1) << 11 << 12;
    A.Row(2) << 21 << 22;
    A.Row(3) << 31 << 32;

Load only values that are actually stored in the matrix. For example

    SymmetricMatrix S(2);
    S.Row(1) << 11;
    S.Row(2) << 21 << 22;

Try to restrict this way of loading data to numbers. You can include expressions, but these must not call a function which includes the same construction.

Remember that matrices are stored by rows and that symmetric matrices are stored as lower triangular matrices when using these methods to enter data.

3.5 Unary operators

next - skip - up - start

The package supports unary operations

    X = -A;           // change sign of elements
    X = A.t();        // transpose
    X = A.i();        // inverse (of square matrix A)
    X = A.Reverse();  // reverse order of elements of vector
                      // or matrix (not band matrix)

3.6 Binary operators

next - skip - up - start

The package supports binary operations

    X = A + B;       // matrix addition
    X = A - B;       // matrix subtraction
    X = A * B;       // matrix multiplication
    X = A.i() * B;   // equation solve (square matrix A)
    X = A | B;       // concatenate horizontally (concatenate the rows)
    X = A & B;       // concatenate vertically (concatenate the columns)
    X = SP(A, B);    // elementwise product of A and B (Schur product)
    X = KP(A, B);    // Kronecker product of A and B
    bool b = A == B; // test whether A and B are equal
    bool b = A != B; // ! (A == B)
    A += B;          // A = A + B;
    A -= B;          // A = A - B;
    A *= B;          // A = A * B;
    A |= B;          // A = A | B;
    A &= B;          // A = A & B;
    <, >, <=, >=     // included for compatibility with STL - see notes

Notes:

  • If you are doing repeated multiplication. For example A*B*C, use brackets to force the order of evaluation to minimise the number of operations. If C is a column vector and A is not a vector, then it will usually reduce the number of operations to use A*(B*C).
  • In the equation solve example case the inverse is not explicitly calculated. An LU decomposition of A is performed and this is applied to B. This is more efficient than calculating the inverse and then multiplying. See also multiple matrix solving.
  • The package does not (yet?) recognise B*A.i() as an equation solve and the inverse of A would be calculated. It is probably better to use (A.t().i()*B.t()).t().
  • Horizontal or vertical concatenation returns a result of type Matrix, RowVector or ColumnVector.
  • If A is m x p, B is m x q, then A | B is m x (p+q) with the k-th row being the elements of the k-th row of A followed by the elements of the k-th row of B.
  • If A is p x n, B is q x n, then A & B is (p+q) x n with the k-th column being the elements of the k-th column of A followed by the elements of the k-th column of B.
  • For complicated concatenations of matrices, consider instead using submatrices.
  • See the section on submatrices on using a submatrix on the RHS of an expression.
  • Two matrices are equal if their difference is zero. They may be of different types. For the CroutMatrix or BandLUMatrix they must be of the same type and have all their elements equal. This is not a very useful operator and is included for compatibility with some container templates.
  • The inequality operators are included for compatibility with the standard template library. If actually called, they will throw an exception. So don't try to sort a list of matrices.
  • A row vector multiplied by a column vector yields a 1x1 matrix, not a Real. To get a Real result use either AsScalar or DotProduct.
  • The result from Kronecker product, KP(A, B), possesses an attribute such as upper triangular, lower triangular, band, symmetric, diagonal if both of the matrices A and B have the attribute. (This differs slightly from the way the January 2002 version of newmat10 worked).

Remember that the product of symmetric matrices is not necessarily symmetric so the following code will not run:

   SymmetricMatrix A, B;
   .... put values in A, B ....
   SymmetricMatrix C = A * B;   // run time error

Use instead

   Matrix C = A * B;

or, if you know the product will be symmetric, use

   SymmetricMatrix C; C << A * B;

3.7 Matrix and scalar

next - skip - up - start

The following expressions multiply the elements of a matrix A by a scalar f: A * f or f * A . Likewise one can divide the elements of a matrix A by a scalar f: A / f .

The expressions A + f and A - f add or subtract a rectangular matrix of the same dimension as A with elements equal to f to or from the matrix A .

The expression f + A is an alternative to A + f. The expression f - A subtracts matrix A from a rectangular matrix of the same dimension as A and with elements equal to f .

The expression A += f replaces A by A + f. Operators -=, *=, /= are similarly defined.

3.8 Scalar functions of a matrix - size & shape

next - skip - up - start

This page describes functions returning the values associated with the size and shape of matrices. The following pages describe other scalar matrix functions.

    int m = A.Nrows();                     // number of rows
    int n = A.Ncols();                     // number of columns
    MatrixType mt = A.Type();              // type of matrix
    Real* s = A.Store();                   // pointer to array of elements
    int l = A.Storage();                   // length of array of elements
    MatrixBandWidth mbw = A.BandWidth();   // upper and lower bandwidths

MatrixType mt = A.Type() returns the type of a matrix. Use mt.Value() to get a string (UT, LT, Rect, Sym, Diag, Band, UB, LB, Crout, BndLU) showing the type (Vector types are returned as Rect).

MatrixBandWidth has member functions Upper() and Lower() for finding the upper and lower bandwidths (number of diagonals above and below the diagonal, both zero for a diagonal matrix). For non-band matrices -1 is returned for both these values.

3.9 Scalar functions of a matrix - maximum & minimum

next - skip - up - start

This page describes functions for finding the maximum and minimum elements of a matrix.

    int i, j;
    Real mv = A.MaximumAbsoluteValue();    // maximum of absolute values
    Real mv = A.MinimumAbsoluteValue();    // minimum of absolute values
    Real mv = A.Maximum();                 // maximum value
    Real mv = A.Minimum();                 // minimum value
    Real mv = A.MaximumAbsoluteValue1(i);  // maximum of absolute values
    Real mv = A.MinimumAbsoluteValue1(i);  // minimum of absolute values
    Real mv = A.Maximum1(i);               // maximum value
    Real mv = A.Minimum1(i);               // minimum value
    Real mv = A.MaximumAbsoluteValue2(i,j);// maximum of absolute values
    Real mv = A.MinimumAbsoluteValue2(i,j);// minimum of absolute values
    Real mv = A.Maximum2(i,j);             // maximum value
    Real mv = A.Minimum2(i,j);             // minimum value

All these functions throw an exception if A has no rows or no columns.

The versions A.MaximumAbsoluteValue1(i), etc return the location of the extreme element in a RowVector, ColumnVector or DiagonalMatrix. The versions A.MaximumAbsoluteValue2(i,j), etc return the row and column numbers of the extreme element. If the extreme value occurs more than once the location of the last one is given.

The versions MaximumAbsoluteValue(A), MinimumAbsoluteValue(A), Maximum(A), Minimum(A) can be used in place of A.MaximumAbsoluteValue(), A.MinimumAbsoluteValue(), A.Maximum(), A.Minimum().

3.10 Scalar functions of a matrix - numerical

next - skip - up - start

    Real r = A.AsScalar();                 // value of 1x1 matrix
    Real ssq = A.SumSquare();              // sum of squares of elements
    Real sav = A.SumAbsoluteValue();       // sum of absolute values
    Real s = A.Sum();                      // sum of values
    Real norm = A.Norm1();                 // maximum of sum of absolute
                                              values of elements of a column
    Real norm = A.NormInfinity();          // maximum of sum of absolute
                                              values of elements of a row
    Real norm = A.NormFrobenius();         // square root of sum of squares
                                           // of the elements
    Real t = A.Trace();                    // trace
    Real d = A.Determinant();              // determinant
    LogAndSign ld = A.LogDeterminant();    // log of determinant
    bool z = A.IsZero();                   // test all elements zero
    bool s = A.IsSingular();               // A is a CroutMatrix or
                                              BandLUMatrix
    Real s = DotProduct(A, B);             // dot product of A and B
                                           // interpreted as vectors

A.LogDeterminant() returns a value of type LogAndSign. If ld is of type LogAndSign use

    ld.Value()    to get the value of the determinant
    ld.Sign()     to get the sign of the determinant (values 1, 0, -1)
    ld.LogValue() to get the log of the absolute value.

Note that the direct use of the function Determinant() will often cause a floating point overflow exception.

A.IsZero() returns Boolean value true if the matrix A has all elements equal to 0.0.

IsSingular is defined only for CroutMatrix and BandLUMatrix. It returns true if one of the diagonal elements of the LU decomposition is exactly zero.

DotProduct(const Matrix& A,const Matrix& B) converts both of the arguments to rectangular matrices, checks that they have the same number of elements and then calculates the first element of A * first element of B + second element of A * second element of B + ... ignoring the row/column structure of A and B. It is primarily intended for the situation where A and B are row or column vectors.

The versions Sum(A), SumSquare(A), SumAbsoluteValue(A), Trace(A), LogDeterminant(A), Determinant(A), Norm1(A), NormInfinity(A), NormFrobenius(A) can be used in place of A.Sum(), A.SumSquare(), A.SumAbsoluteValue(), A.Trace(), A.LogDeterminant(), A.Norm1(), A.NormInfinity(), A.NormFrobenius().

3.11 Submatrices

next - skip - up - start

    A.SubMatrix(fr,lr,fc,lc)

This selects a submatrix from A. The arguments fr,lr,fc,lc are the first row, last row, first column, last column of the submatrix with the numbering beginning at 1.

I allow lr = fr-1 or lc = fc-1 or to indicate that a matrix of zero rows or columns is to be returned.

A submatrix command may be used in any matrix expression or on the left hand side of =, << or Inject. Inject does not check no information loss. You can also use the construction

    Real c; .... A.SubMatrix(fr,lr,fc,lc) = c;

to set a submatrix equal to a constant.

The following are variants of SubMatrix:

    A.SymSubMatrix(f,l)             //   This assumes fr=fc and lr=lc.
    A.Rows(f,l)                     //   select rows
    A.Row(f)                        //   select single row
    A.Columns(f,l)                  //   select columns
    A.Column(f)                     //   select single column

In each case f and l mean the first and last row or column to be selected (starting at 1).

I allow l = f-1 to indicate that a matrix of zero rows or columns is to be returned.

If SubMatrix or its variant occurs on the right hand side of an = or << or within an expression think of its type as follows

    A.SubMatrix(fr,lr,fc,lc)           If A is RowVector or
                                       ColumnVector then same type
                                       otherwise type Matrix
    A.SymSubMatrix(f,l)                Same type as A
    A.Rows(f,l)                        Type Matrix
    A.Row(f)                           Type RowVector
    A.Columns(f,l)                     Type Matrix
    A.Column(f)                        Type ColumnVector

If SubMatrix or its variant appears on the left hand side of = or << , think of its type being Matrix. Thus L.Row(1) where L is LowerTriangularMatrix expects L.Ncols() elements even though it will use only one of them. If you are using = the program will check for no loss of data.

A SubMatrix can appear on the left-hand side of += or -= with a matrix expression on the right-hand side. It can also appear on the left-hand side of +=, -=, *= or /= with a Real on the right-hand side. In each case there must be no loss of information.

The Row version can appear on the left hand side of << for loading literal data into a row. Load only the number of elements that are actually going to be stored in memory.

Do not use the += and -= operations with a submatrix of a SymmetricMatrix or BandSymmetricMatrix on the LHS and a Real on the RHS.

You can't pass a submatrix (or any of its variants) as a reference non-constant matrix in a function argument. For example, the following will not work:

   void YourFunction(Matrix& A);
   ...
   Matrix B(10,10);
   YourFunction(B.SubMatrix(1,5,1,5))    // won't compile

If you are are using the submatrix facility to build a matrix from a small number of components, consider instead using the concatenation operators.

3.12 Change dimensions

next - skip - up - start

The following operations change the dimensions of a matrix. The values of the elements are lost.

    A.ReSize(nrows,ncols);        // for type Matrix or nricMatrix
    A.ReSize(n);                  // for all other types, except Band
    A.ReSize(n,lower,upper);      // for BandMatrix
    A.ReSize(n,lower);            // for LowerBandMatrix
    A.ReSize(n,upper);            // for UpperBandMatrix
    A.ReSize(n,lower);            // for SymmetricBandMatrix
    A.ReSize(B);                  // set dims to those of B 

Use A.CleanUp() to set the dimensions of A to zero and release all the heap memory.

A.ReSize(B) sets the dimensions of A to those of a matrix B. This includes the band-width in the case of a band matrix. It is an error for A to be a band matrix and B not a band matrix (or diagonal matrix).

Remember that ReSize destroys values. If you want to ReSize, but keep the values in the bit that is left use something like

   ColumnVector V(100);
   ...                            // load values
   V = V.Rows(1,50);              // to get first 50 values.

If you want to extend a matrix or vector use something like

   ColumnVector V(50);
   ...                            // load values
   { V.Release(); ColumnVector X=V; V.ReSize(100); V.Rows(1,50)=X; }
                                  // V now length 100

3.13 Change type

next - skip - up - start

The following functions interpret the elements of a matrix (stored row by row) to be a vector or matrix of a different type. Actual copying is usually avoided where these occur as part of a more complicated expression.

    A.AsRow()
    A.AsColumn()
    A.AsDiagonal()
    A.AsMatrix(nrows,ncols)
    A.AsScalar()

The expression A.AsScalar() is used to convert a 1 x 1 matrix to a scalar.

3.14 Multiple matrix solve

next - skip - up - start

To solve the matrix equation Ay = b where A is a square matrix of equation coefficients, y is a column vector of values to be solved for, and b is a column vector, use the code

    int n = something
    Matrix A(n,n); ColumnVector b(n);
    ... put values in A and b
    ColumnVector y = A.i() * b;       // solves matrix equation

The following notes are for the case where you want to solve more than one matrix equation with different values of b but the same A. Or where you want to solve a matrix equation and also find the determinant of A. In these cases you probably want to avoid repeating the LU decomposition of A for each solve or determinant calculation.

If A is a square or symmetric matrix use

    CroutMatrix X = A;                // carries out LU decomposition
    Matrix AP = X.i()*P; Matrix AQ = X.i()*Q;
    LogAndSign ld = X.LogDeterminant();

rather than

    Matrix AP = A.i()*P; Matrix AQ = A.i()*Q;
    LogAndSign ld = A.LogDeterminant();

since each operation will repeat the LU decomposition.

If A is a BandMatrix or a SymmetricBandMatrix begin with

    BandLUMatrix X = A;               // carries out LU decomposition

A CroutMatrix or a BandLUMatrix can't be manipulated or copied. Use references as an alternative to copying.

Alternatively use

    LinearEquationSolver X = A;

This will choose the most appropriate decomposition of A. That is, the band form if A is banded; the Crout decomposition if A is square or symmetric and no decomposition if A is triangular or diagonal.

3.15 Memory management

next - skip - up - start

The package does not support delayed copy. Several strategies are required to prevent unnecessary matrix copies.

Where a matrix is called as a function argument use a constant reference. For example

    YourFunction(const Matrix& A)

rather than

    YourFunction(Matrix A)

Skip the rest of this section on your first reading.

Gnu g++ (< 2.6) users please read on: if you are returning matrix values from a function, then you must use the ReturnMatrix construct.

A second place where it is desirable to avoid unnecessary copies is when a function is returning a matrix. Matrices can be returned from a function with the return command as you would expect. However these may incur one and possibly two copyings of the matrix. To avoid this use the following instructions.

Make your function of type ReturnMatrix . Then precede the return statement with a Release statement (or a ReleaseAndDelete statement if the matrix was created with new). For example

    ReturnMatrix MakeAMatrix()
    {
       Matrix A;                // or any other matrix type
       ......
       A.Release(); return A;
    }

or

    ReturnMatrix MakeAMatrix()
    {
       Matrix* m = new Matrix;
       ......
       m->ReleaseAndDelete(); return *m;
    }

If your compiler objects to this code, replace the return statements with

    return A.ForReturn();

or

    return m->ForReturn();

If you are using AT&T C++ you may wish to replace return A; by return (ReturnMatrix)A; to avoid a warning message; but this will give a runtime error with Gnu. (You can't please everyone.)


Do not forget to make the function of type ReturnMatrix; otherwise you may get incomprehensible run-time errors.


You can also use .Release() or ->ReleaseAndDelete() to allow a matrix expression to recycle space. Suppose you call

    A.Release();

just before A is used just once in an expression. Then the memory used by A is either returned to the system or reused in the expression. In either case, A's memory is destroyed. This procedure can be used to improve efficiency and reduce the use of memory.

Use ->ReleaseAndDelete for matrices created by new if you want to completely delete the matrix after it is accessed.

3.16 Efficiency

next - skip - up - start

The package tends to be not very efficient for dealing with matrices with short rows. This is because some administration is required for accessing rows for a variety of types of matrices. To reduce the administration a special multiply routine is used for rectangular matrices in place of the generic one. Where operations can be done without reference to the individual rows (such as adding matrices of the same type) appropriate routines are used.

When you are using small matrices (say smaller than 10 x 10) you may find it faster to use rectangular matrices rather than the triangular or symmetric ones.

3.17 Output

next - skip - up - start

To print a matrix use an expression like

   Matrix A;
   ......
   cout << setw(10) << setprecision(5) << A;

This will work only with systems that support the standard input/output routines including manipulators. You need to #include the files iostream.h, iomanip.h, newmatio.h in your C++ source files that use this facility. The files iostream.h, iomanip.h will be included automatically if you include the statement #define WANT_STREAM at the beginning of your source file. So you can begin your file with either

   #define WANT_STREAM
   #include "newmatio.h"

or

   #include <iostream.h>
   #include <iomanip.h>
   #include "newmatio.h"

The present version of this routine is useful only for matrices small enough to fit within a page or screen width.

To print several vectors or matrices in columns use a concatenation operator:

   ColumnVector A, B;
   .....
   cout << setw(10) << setprecision(5) << (A | B);

3.18 Unspecified type

next - skip - up - start

Skip this section on your first reading.

If you want to work with a matrix of unknown type, say in a function. You can construct a matrix of type GenericMatrix. Eg

   Matrix A;
   .....                                  // put some values in A
   GenericMatrix GM = A;

A GenericMatrix matrix can be used anywhere where a matrix expression can be used and also on the left hand side of an =. You can pass any type of matrix (excluding the Crout and BandLUMatrix types) to a const GenericMatrix& argument in a function. However most scalar functions including Nrows(), Ncols(), Type() and element access do not work with it. Nor does the ReturnMatrix construct. See also the paragraph on LinearEquationSolver.

An alternative and less flexible approach is to use BaseMatrix or GeneralMatrix.

Suppose you wish to write a function which accesses a matrix of unknown type including expressions (eg A*B). Then use a layout similar to the following:

   void YourFunction(BaseMatrix& X)
   {
      GeneralMatrix* gm = X.Evaluate();   // evaluate an expression
                                          // if necessary
      ........                            // operations on *gm
      gm->tDelete();                      // delete *gm if a temporary
   }

See, as an example, the definitions of operator<< in newmat9.cpp.

Under certain circumstances; particularly where X is to be used just once in an expression you can leave out the Evaluate() statement and the corresponding tDelete(). Just use X in the expression.

If you know YourFunction will never have to handle a formula as its argument you could also use

   void YourFunction(const GeneralMatrix& X)
   {
      ........                            // operations on X
   }

Do not try to construct a GeneralMatrix or BaseMatrix.

3.19 Cholesky decomposition

next - skip - up - start

Suppose S is symmetric and positive definite. Then there exists a unique lower triangular matrix L such that L * L.t() = S. To calculate this use

    SymmetricMatrix S;
    ......
    LowerTriangularMatrix L = Cholesky(S);

If S is a symmetric band matrix then L is a band matrix and an alternative procedure is provided for carrying out the decomposition:

    SymmetricBandMatrix S;
    ......
    LowerBandMatrix L = Cholesky(S);

3.20 QR decomposition

next - skip - up - start

This is a variant on the usual QR transformation.

Start with matrix (dimensions shown to left and below the matrix)

       / 0    0 \      s
       \ X    Y /      n

         s    t

Our version of the QR decomposition multiplies this matrix by an orthogonal matrix Q to get

       / U    M \      s
       \ 0    Z /      n

         s    t

where U is upper triangular (the R of the QR transform). That is

      Q  / 0   0 \  =  / U   M \
         \ X   Y /     \ 0   Z / 

This is good for solving least squares problems: choose b (matrix or column vector) to minimise the sum of the squares of the elements of

         Y - X*b

Then choose b = U.i()*M; The residuals Y - X*b are in Z.

This is the usual QR transformation applied to the matrix X with the square zero matrix concatenated on top of it. It gives the same triangular matrix as the QR transform applied directly to X and generally seems to work in the same way as the usual QR transform. However it fits into the matrix package better and also gives us the residuals directly. It turns out to be essentially a modified Gram-Schmidt decomposition.

Two routines are provided in newmat:

    QRZ(X, U);

replaces X by orthogonal columns and forms U.

    QRZ(X, Y, M);

uses X from the first routine, replaces Y by Z and forms M.

The are also two routines QRZT(X, L) and QRZT(X, Y, M) which do the same decomposition on the transposes of all these matrices. QRZT replaces the routines HHDecompose in earlier versions of newmat. HHDecompose is still defined but just calls QRZT.

For an example of the use of this decomposition see the file example.cpp.

3.21 Singular value decomposition

next - skip - up - start

The singular value decomposition of an m x n Matrix A (where m >= n) is a decomposition

    A  = U * D * V.t()

where U is m x n with U.t() * U equalling the identity, D is an n x n DiagonalMatrix and V is an n x n orthogonal matrix (type Matrix in Newmat).

Singular value decompositions are useful for understanding the structure of ill-conditioned matrices, solving least squares problems, and for finding the eigenvalues of A.t() * A.

To calculate the singular value decomposition of A (with m >= n) use one of

    SVD(A, D, U, V);                  // U = A is OK
    SVD(A, D);
    SVD(A, D, U);                     // U = A is OK
    SVD(A, D, U, false);              // U (can = A) for workspace only
    SVD(A, D, U, V, false);           // U (can = A) for workspace only

where A, U and V are of type Matrix and D is a DiagonalMatrix. The values of A are not changed unless A is also inserted as the third argument.

The elements of D are sorted in descending order.

Remember that the SVD decomposition is not completely unique. The signs of the elements in a column of U may be reversed if the signs in the corresponding column in V are reversed. If a number of the singular values are identical one can apply an orthogonal transformation to the corresponding columns of U and the corresponding columns of V.

3.22 Eigenvalue decomposition

next - skip - up - start

An eigenvalue decomposition of a SymmetricMatrix A is a decomposition

    A  = V * D * V.t()

where V is an orthogonal matrix (type Matrix in Newmat) and D is a DiagonalMatrix.

Eigenvalue analyses are used in a wide variety of engineering, statistical and other mathematical analyses.

The package includes two algorithms: Jacobi and Householder. The first is extremely reliable but much slower than the second.

The code is adapted from routines in Handbook for Automatic Computation, Vol II, Linear Algebra by Wilkinson and Reinsch, published by Springer Verlag.

    Jacobi(A,D,S,V);                  // A, S symmetric; S is workspace,
                                      //    S = A is OK; V is a matrix
    Jacobi(A,D);                      // A symmetric
    Jacobi(A,D,S);                    // A, S symmetric; S is workspace,
                                      //    S = A is OK
    Jacobi(A,D,V);                    // A symmetric; V is a matrix

    EigenValues(A,D);                 // A symmetric
    EigenValues(A,D,S);               // A, S symmetric; S is for back
                                      //    transforming, S = A is OK
    EigenValues(A,D,V);               // A symmetric; V is a matrix

where A, S are of type SymmetricMatrix, D is of type DiagonalMatrix and V is of type Matrix. The values of A are not changed unless A is also inserted as the third argument. If you need eigenvectors use one of the forms with matrix V. The eigenvectors are returned as the columns of V.

The elements of D are sorted in ascending order.

Remember that an eigenvalue decomposition is not completely unique - see the comments about the SVD decomposition.

3.23 Sorting

next - skip - up - start

To sort the values in a matrix or vector, A, (in general this operation makes sense only for vectors and diagonal matrices) use one of

    SortAscending(A);

    SortDescending(A);

I use the quicksort algorithm. The algorithm is similar to that in Sedgewick's algorithms in C++. If the sort seems to be failing (as quicksort can do) an exception is thrown.

You will get incorrect results if you try to sort a band matrix - but why would you want to sort a band matrix?

3.24 Fast Fourier transform

next - skip - up - start

   FFT(X, Y, F, G);                         // F=X and G=Y are OK

where X, Y, F, G are column vectors. X and Y are the real and imaginary input vectors; F and G are the real and imaginary output vectors. The lengths of X and Y must be equal and should be the product of numbers less than about 10 for fast execution.

The formula is

          n-1
   h[k] = SUM  z[j] exp (-2 pi i jk/n)
          j=0

where z[j] is stored complex and stored in X(j+1) and Y(j+1). Likewise h[k] is complex and stored in F(k+1) and G(k+1). The fast Fourier algorithm takes order n log(n) operations (for good values of n) rather than n**2 that straight evaluation (see the file tmtf.cpp) takes.

I use one of two methods:

  • A program originally written by Sande and Gentleman. This requires that n can be expressed as a product of small numbers.
  • A method of Carl de Boor (1980), Siam J Sci Stat Comput, pp 173-8. The sines and cosines are calculated explicitly. This gives better accuracy, at an expense of being a little slower than is otherwise possible. This is slower than the Sande-Gentleman program but will work for all n --- although it will be very slow for bad values of n.

Related functions

   FFTI(F, G, X, Y);                        // X=F and Y=G are OK
   RealFFT(X, F, G);
   RealFFTI(F, G, X);

FFTI is the inverse transform for FFT. RealFFT is for the case when the input vector is real, that is Y = 0. I assume the length of X, denoted by n, is even. That is, n must be divisible by 2. The program sets the lengths of F and G to n/2 + 1. RealFFTI is the inverse of RealFFT.

See also the section on fast trigonometric transforms.

3.25 Fast trigonometric transforms

next - skip - up - start

These are the sin and cosine transforms as defined by Charles Van Loan (1992) in Computational frameworks for the fast Fourier transform published by SIAM. See page 229. Some other authors use slightly different conventions. All the functions call the fast Fourier transforms and require an even transform length, denoted by m in these notes. That is, m must be divisible by 2. As with the FFT m should be the product of numbers less than about 10 for fast execution.

The functions I define are

   DCT(U,V);                // U, V are ColumnVectors, length m+1
   DCT_inverse(V,U);        // inverse of DCT
   DST(U,V);                // U, V are ColumnVectors, length m+1
   DST_inverse(V,U);        // inverse of DST
   DCT_II(U,V);             // U, V are ColumnVectors, length m
   DCT_II_inverse(V,U);     // inverse of DCT_II
   DST_II(U,V);             // U, V are ColumnVectors, length m
   DST_II_inverse(V,U);     // inverse of DST_II

where the first argument is the input and the second argument is the output. V = U is OK. The length of the output ColumnVector is set by the functions.

Here are the formulae:

DCT

                   m-1                             k
   v[k] = u[0]/2 + SUM { u[j] cos (pi jk/m) } + (-) u[m]/2
                   j=1

for k = 0...m, where u[j] and v[k] are stored in U(j+1) and V(k+1).

DST

          m-1
   v[k] = SUM { u[j] sin (pi jk/m) }
          j=1

for k = 1...(m-1), where u[j] and v[k] are stored in U(j+1) and V(k+1)and where u[0] and u[m] are ignored and v[0] and v[m] are set to zero. For the inverse function v[0] and v[m] are ignored and u[0] and u[m] are set to zero.

DCT_II

          m-1
   v[k] = SUM { u[j] cos (pi (j+1/2)k/m) }
          j=0

for k = 0...(m-1), where u[j] and v[k] are stored in U(j+1) and V(k+1).

DST_II

           m
   v[k] = SUM { u[j] sin (pi (j-1/2)k/m) }
          j=1

for k = 1...m, where u[j] and v[k] are stored in U(j) and V(k).

Note that the relationship between the subscripts in the formulae and those used in newmat is different for DST_II (and DST_II_inverse).

3.26 Interface to Numerical Recipes in C

next - skip - up - start

This package can be used with the vectors and matrices defined in Numerical Recipes in C. You need to edit the routines in Numerical Recipes so that the elements are of the same type as used in this package. Eg replace float by double, vector by dvector and matrix by dmatrix, etc. You may need to edit the function definitions to use the version acceptable to your compiler (if you are using the first edition of NRIC). You may need to enclose the code from Numerical Recipes in extern "C" { ... }. You will also need to include the matrix and vector utility routines.

Then any vector in Numerical Recipes with subscripts starting from 1 in a function call can be accessed by a RowVector, ColumnVector or DiagonalMatrix in the present package. Similarly any matrix with subscripts starting from 1 can be accessed by an nricMatrix in the present package. The class nricMatrix is derived from Matrix and can be used in place of Matrix. In each case, if you wish to refer to a RowVector, ColumnVector, DiagonalMatrix or nricMatrix X in an function from Numerical Recipes, use X.nric() in the function call.

Numerical Recipes cannot change the dimensions of a matrix or vector. So matrices or vectors must be correctly dimensioned before a Numerical Recipes routine is called.

For example

   SymmetricMatrix B(44);
   .....                             // load values into B
   nricMatrix BX = B;                // copy values to an nricMatrix
   DiagonalMatrix D(44);             // Matrices for output
   nricMatrix V(44,44);              //    correctly dimensioned
   int nrot;
   jacobi(BX.nric(),44,D.nric(),V.nric(),&nrot);
                                     // jacobi from NRIC
   cout << D;                        // print eigenvalues

3.27 Exceptions

next - skip - up - start

Here is the class structure for exceptions:

Exception
  Logic_error
    ProgramException                 miscellaneous matrix error
    IndexException                   index out of bounds
    VectorException                  unable to convert matrix to vector
    NotSquareException               matrix is not square (invert, solve)
    SubMatrixDimensionException      out of bounds index of submatrix
    IncompatibleDimensionsException  (multiply, add etc)
    NotDefinedException              operation not defined (eg <)
    CannotBuildException             copying a matrix where copy is undefined
    InternalException                probably an error in newmat
  Runtime_error
    NPDException                     matrix not positive definite (Cholesky)
    ConvergenceException             no convergence (e-values, non-linear, sort)
    SingularException                matrix is singular (invert, solve)
    SolutionException                no convergence in solution routine
    OverflowException                floating point overflow
  Bad_alloc                          out of space (new fails)

I have attempted to mimic the exception class structure in the C++ standard library, by defining the Logic_error and Runtime_error classes.

Suppose you have edited include.h to use my simulated exceptions or to disable exceptions. If there is no catch statement or exceptions are disabled then my Terminate() function in myexcept.h is called when you throw an exception. This prints out an error message, the dimensions and types of the matrices involved, the name of the routine detecting the exception, and any other information set by the Tracer class. Also see the section on error messages for additional notes on the messages generated by the exceptions.

You can also print this information in a catch clause by printing Exception::what().

If you are using compiler supported exceptions then see the section on catching exceptions

See the file test_exc.cpp as an example of catching an exception and printing the error message.

The 08 version of newmat defined a member function void SetAction(int) to help customise the action when an exception is called. This has been deleted in the 09 and 10 versions. Now include an instruction such as cout << Exception::what() << endl; in the Catch or CatchAll block to determine the action.

The library includes the alternatives of using the inbuilt exceptions provided by a compiler, simulating exceptions, or disabling exceptions. See customising for selecting the correct exception option.

The rest of this section describes my partial simulation of exceptions for compilers which do not support C++ exceptions. I use Carlos Vidal's article in the September 1992 C Users Journal as a starting point.

Newmat does a partial clean up of memory following throwing an exception - see the next section. However, the present version will leave a little heap memory unrecovered under some circumstances. I would not expect this to be a major problem, but it is something that needs to be sorted out.

The functions/macros I define are Try, Throw, Catch, CatchAll and CatchAndThrow. Try, Throw, Catch and CatchAll correspond to try, throw, catch and catch(...) in the C++ standard. A list of Catch clauses must be terminated by either CatchAll or CatchAndThrow but not both. Throw takes an Exception as an argument or takes no argument (for passing on an exception). I do not have a version of Throw for specifying which exceptions a function might throw. Catch takes an exception class name as an argument; CatchAll and CatchAndThrow don't have any arguments. Try, Catch and CatchAll must be followed by blocks enclosed in curly brackets.

I have added another macro ReThrow to mean a rethrow, Throw(). This was necessary to enable the package to be compatible with both my exception package and C++ exceptions.

If you want to throw an exception, use a statement like

   Throw(Exception("Error message\n"));

It is important to have the exception declaration in the Throw statement, rather than as a separate statement.

All exception classes must be derived from the class, Exception, defined in newmat and can contain only static variables. See the examples in newmat if you want to define additional exceptions.

Note that the simulation exception mechanism does not work if you define arrays of matrices.

3.28 Cleanup after an exception

next - skip - up - start

This section is about the simulated exceptions used in newmat. It is irrelevant if you are using the exceptions built into a compiler or have set the disable-exceptions option.

The simulated exception mechanisms in newmat are based on the C functions setjmp and longjmp. These functions do not call destructors so can lead to garbage being left on the heap. (I refer to memory allocated by new as heap memory). For example, when you call

   Matrix A(20,30);

a small amount of space is used on the stack containing the row and column dimensions of the matrix and 600 doubles are allocated on the heap for the actual values of the matrix. At the end of the block in which A is declared, the destructor for A is called and the 600 doubles are freed. The locations on the stack are freed as part of the normal operations of the stack. If you leave the block using a longjmp command those 600 doubles will not be freed and will occupy space until the program terminates.

To overcome this problem newmat keeps a list of all the currently declared matrices and its exception mechanism will return heap memory when you do a Throw and Catch.

However it will not return heap memory from objects from other packages.

If you want the mechanism to work with another class you will have to do four things:

  1. derive your class from class Janitor defined in except.h;
  2. define a function void CleanUp() in that class to return all heap memory;
  3. include the following lines in the class definition
          public:
             void* operator new(size_t size)
             { do_not_link=true; void* t = ::operator new(size); return t; }
             void operator delete(void* t) { ::operator delete(t); }
    
  4. be sure to include a copy constructor in you class definition, that is, something like
          X(const X&);
    

Note that the function CleanUp() does somewhat the same duties as the destructor. However CleanUp() has to do the cleaning for the class you are working with and also the classes it is derived from. So it will often be wrong to use exactly the same code for both CleanUp() and the destructor or to define your destructor as a call to CleanUp().

3.29 Non-linear applications

next - skip - up - start

Files solution.h, solution.cpp contain a class for solving for x in y = f(x) where x is a one-dimensional continuous monotonic function. This is not a matrix thing at all but is included because it is a useful thing and because it is a simpler version of the technique used in the non-linear least squares.

Files newmatnl.h, newmatnl.cpp contain a series of classes for non-linear least squares and maximum likelihood. These classes work on very well-behaved functions but need upgrading for less well-behaved functions.

Documentation for both of these is in the definition files. Simple examples are in sl_ex.cpp, nl_ex.cpp and garch.cpp.

3.30 Standard template library

next - skip - up - start

The standard template library (STL) is the set of container templates (vector, deque, list etc) defined by the C++ standards committee. Newmat is intended to be compatible with the STL in the sense that you can store matrices in the standard containers. I have defined == and inequality operators which seem to be required by some versions of the STL. Probably there will have to be some other changes. My experiments with the Rogue Wave STL that comes with Borland C++ 5.0 showed that some things worked and some things unexpectedly didn't work.

If you want to use the container classes with Newmat please note

  • Don't use simulated exceptions.
  • Make sure the option DO_FREE_CHECK is not turned on.
  • You can store only one type of matrix in a container. If you want to use a variety of types use the GenericMatrix type or store pointers to the matrices.
  • The vector and deque container templates like to copy their elements. For the vector container this happens when you insert an element anywhere except at the end or when you append an element and the current vector storage overflows. Since Newmat does not have copy-on-write this could get very inefficient. (Later versions may have copy-on-write for the GenericMatrix type).
  • You won't be able to sort the container or do anything that would call an inequality operator.

I doubt whether the STL container will be used often for matrices. So I don't think these limitations are very critical. If you think otherwise, please tell me.

3.31 Namespace

next - skip - up - start

Namespace is a new facility in C++. Its purpose is to avoid name clashes between different libraries. I have included the namespace capability. Activate the line #define use_namespace in include.h. Then include either the statement

   using namespace NEWMAT;

at the beginning of any file that needs to access the newmat library or

   using namespace RBD_LIBRARIES;

at the beginning of any file that needs to access all my libraries.

This works correctly with Borland C++ version 5.

Microsoft Visual C++ version 5 works in my example and test files, but fails with apparently insignificant changes (it may be more reliable if you have applied service pack 3). If you #include "newmatap.h", but no other newmat include file, then also #include "newmatio.h". It seems to work with Microsoft Visual C++ version 6 if you have applied at least service pack 2.

My use of namespace works with Gnu g++ version 3.3

I have defined the following namespaces:

  • RBD_COMMON for functions and classes used by most of my libraries
  • NEWMAT for the newmat library
  • RBD_LIBRARIES for all my libraries

4. Error messages

next - skip - up - start

Most error messages are self-explanatory. The message gives the size of the matrices involved. Matrix types are referred to by the following codes:

   Matrix or vector                   Rect
   Symmetric matrix                   Sym
   Band matrix                        Band
   Symmetric band matrix              SmBnd
   Lower triangular matrix            LT
   Lower triangular band matrix       LwBnd
   Upper triangular matrix            UT
   Upper triangular band matrix       UpBnd
   Diagonal matrix                    Diag
   Crout matrix (LU matrix)           Crout
   Band LU matrix                     BndLU

Other codes should not occur.

See the section on exceptions for more details on the structure of the exception classes.

I have defined a class Tracer that is intended to help locate the place where an error has occurred. At the beginning of a function I suggest you include a statement like

   Tracer tr("name");

where name is the name of the function. This name will be printed as part of the error message, if an exception occurs in that function, or in a function called from that function. You can change the name as you proceed through a function with the ReName function

   tr.ReName("new name");

if, for example, you want to track progress through the function.

5. Notes on the design of the library

next - skip - up - start

5.1 Safety, usability, efficiency
5.2 Matrix vs array library
5.3 Design questions
5.4 Data storage
5.5 Memory management - 1
5.6 Memory management - 2
5.7 Evaluation of expressions
5.8 Explosion in the number of operations
5.9 Destruction of temporaries
5.10 A calculus of matrix types
5.11 Pointer arithmetic
5.12 Error handling
5.13 Sparse matrices
5.14 Complex matrices

I describe some of the ideas behind this package, some of the decisions that I needed to make and give some details about the way it works. You don't need to read this part of the documentation in order to use the package.

It isn't obvious what is the best way of going about structuring a matrix package. I don't think you can figure this out with thought experiments. Different people have to try out different approaches. And someone else may have to figure out which is best. Or, more likely, the ultimate packages will lift some ideas from each of a variety of trial packages. So, I don't claim my package is an ultimate package, but simply a trial of a number of ideas. The following pages give some background on these ideas.

5.1 Safety, usability, efficiency

next - skip - up - start

Some general comments

A library like newmat needs to balance safety, usability and efficiency.

By safety, I mean getting the right answer, and not causing crashes or damage to the computer system.

By usability, I mean being easy to learn and use, including not being too complicated, being intuitive, saving the users' time, being nice to use.

Efficiency means minimising the use of computer memory and time.

In the early days of computers the emphasis was on efficiency. But computer power gets cheaper and cheaper, halving in price every 18 months. On the other hand the unaided human brain is probably not a lot better than it was 100,000 years ago! So we should expect the balance to shift to put more emphasis on safety and usability and a little less on efficiency. So I don't mind if my programs are a little less efficient than programs written in pure C (or Fortran) if I gain substantially in safety and usability. But I would mind if they were a lot less efficient.

Type of use

Second reason for putting extra emphasis on safety and usability is the way I and, I suspect, most other users actually use newmat. Most completed programs are used only a few times. Some result is required for a client, paper or thesis. The program is developed and tested, the result is obtained, and the program archived. Of course bits of the program will be recycled for the next project. But it may be less usual for the same program to be run over and over again. So the cost, computer time + people time, is in the development time and often, much less in the actual time to run the final program. So good use of people time, especially during development is really important. This means you need highly usable libraries.

So if you are dealing with matrices, you want the good interface that I have tried to provide in newmat, and, of course, reliable methods underneath it.

Of course, efficiency is still important. We often want to run the biggest problem our computer will handle and often a little bigger. The C++ language almost lets us have both worlds. We can define a reasonably good interface, and get good efficiency in the use of the computer.

Levels of access

We can imagine the black box model of a newmat. Suppose the inside is hidden but can be accessed by the methods described in the reference section. Then the interface is reasonably consistent and intuitive. Matrices can be accessed and manipulated in much the same way as doubles or ints in regular C. All accesses are checked. It is most unlikely that an incorrect index will crash the system. In general, users do not need to use pointers, so one shouldn't get pointers pointing into space. And, hopefully, you will get simpler code and so less errors.

There are some exceptions to this. In particular, the C-like subscripts are not checked for validity. They give faster access but with a lower level of safety.

Then there is the Store() function which takes you to the data array within a matrix. This takes you right inside the black box. But this is what you have to use if you are writing, for example, a new matrix factorisation, and require fast access to the data array. I have tried to write code to simplify access to the interior of a rectangular matrix, see file newmatrm.cpp, but I don't regard this as very successful, as yet, and have not included it in the documentation. Ideally we should have improved versions of this code for each of the major types of matrix. But, in reality, most of my matrix factorisations are written in what is basically the C language with very little C++.

So our box is not very black. You have a choice of how far you penetrate. On the outside you have a good level of safety, but in some cases efficiency is compromised a little. If you penetrate inside the box safety is reduced but you can get better efficiency.

Some performance data

This section looks at the performance on newmat for simple sums, comparing it with C code and with a simple array program.

The following table lists the time (in seconds) for carrying out the operations X=A+B;, X=A+B+C;, X=A+B+C+D;, X=A+B+C+D+E; where X,A,B,C,D,E are of type ColumnVector, with a variety of programs. I am using Microsoft VC++, version 6 in console mode under windows 2000 on a PC with a 1 ghz Pentium III and 512 mbytes of memory.

    length    iters. newmat      C C-res.  subs.  array
X = A + B
         2   5000000   27.8    0.3    8.8    1.9    9.5 
        20    500000    3.0    0.3    1.1    1.9    1.2 
       200     50000    0.5    0.3    0.4    1.9    0.3 
      2000      5000    0.4    0.3    0.4    2.0    1.0 
     20000       500    4.5    4.5    4.5    6.7    4.4 
    200000        50    5.2    4.7    5.5    5.8    5.2 

X = A + B + C
         2   5000000   36.6    0.4    8.9    2.5   12.2 
        20    500000    4.0    0.4    1.2    2.5    1.6 
       200     50000    0.8    0.3    0.5    2.5    0.5 
      2000      5000    3.6    4.4    4.6    9.0    4.4 
     20000       500    6.8    5.4    5.4    9.6    6.8 
    200000        50    8.6    6.0    6.7    7.1    8.6 

X = A + B + C + D
         2   5000000   44.0    0.7    9.3    3.1   14.6 
        20    500000    4.9    0.6    1.5    3.1    1.9 
       200     50000    1.0    0.6    0.8    3.2    0.8 
      2000      5000    5.6    6.6    6.8   11.5    5.9 
     20000       500    9.0    6.7    6.8   11.0    8.5 
    200000        50   11.9    7.1    7.9    9.5   12.0 

X = A + B + C + D + E
         2   5000000   50.6    1.0    9.5    3.8   17.1 
        20    500000    5.7    0.8    1.7    3.9    2.4 
       200     50000    1.3    0.9    1.0    3.9    1.0 
      2000      5000    7.0    8.3    8.2   13.8    7.1 
     20000       500   11.5    8.1    8.4   13.2   11.0 
    200000        50   15.2    8.7    9.5   12.4   15.4 

I have graphed the results and included rather more array lengths.

The first column gives the lengths of the arrays, the second the number of iterations and the remaining columns the total time required in seconds. If the only thing that consumed time was the double precision addition then the numbers within each block of the table would be the same. The summation is repeated 5 times within each loop, for example:

   for (i=1; i<=m; ++i)
   {
      X1 = A1+B1+C1; X2 = A2+B2+C2; X3 = A3+B3+C3;
      X4 = A4+B4+C4; X5 = A5+B5+C5;
   }

The column labelled newmat is using the standard newmat add. The column labelled C uses the usual C method: while (j1--) *x1++ = *a1++ + *b1++; . The following column also includes an X.ReSize() in the outer loop to correspond to the reassignment of memory that newmat would do. In the next column the calculation is using the usual C style for loop and accessing the elements using newmat subscripts such as A(i). The final column is the time taken by a simple array package. This uses an alternative method for avoiding temporaries and unnecessary copies that does not involve runtime tests. It does its sums in blocks of 4 and copies in blocks of 8 in the same way that newmat does.

Here are my conclusions.

  • Newmat does very badly for length 2 and doesn't do well for length 20. There is a lot of code in newmat for determining which sum algorithm to use and it is not surprising that this impacts on performance for small lengths. However the array program is also having difficulty with length 2 so it is unlikely that the problem could be completely eliminated.
  • For arrays of length 2000 or longer newmat is doing about as well as C and slightly better than C with resize in the X=A+B table. For the other two tables it tends to be slower, but not dramatically so.
  • It is really important for fast processing with the Pentium III to stay within the Pentium cache.
  • Addition using the newmat subscripts, while considerably slower than the others, is still surprisingly good for the longer arrays.
  • The array program and newmat are similar for lengths 2000 or higher (the longer times for the array program for the longest arrays shown on the graph are probably a quirk of the timing program).

In summary: for the situation considered here, newmat is doing very well for large ColumnVectors, even for sums with several terms, but not so well for shorter ColumnVectors.

5.2 Matrix vs array library

next - skip - up - start

The newmat library is for the manipulation of matrices, including the standard operations such as multiplication as understood by numerical analysts, engineers and mathematicians.

A matrix is a two dimensional array of numbers. However, very special operations such as matrix multiplication are defined specifically for matrices. This means that a matrix library, as I understand the term, is different from a general array library. Here are some contrasting properties.

Feature Matrix library Array library
Expressions Matrix expressions; * means matrix multiply; inverse function Arithmetic operations, if supported, mean elementwise combination of arrays
Element access Access to the elements of a matrix High speed access to elements directly and perhaps with iterators
Elementary functions For example: determinant, trace Matrix multiplication as a function
Advanced functions For example: eigenvalue analysis  
Element types Real and possibly complex Wide range - real, integer, string etc
Types Rectangular, symmetric, diagonal, etc One, two and three dimensional arrays, at least

Both types of library need to support access to sub-matrices or sub-arrays, have good efficiency and storage management, and graceful exit for errors. In both cases, we probably need two versions, one optimised for large matrices or arrays and one for small matrices or arrays.

It may be possible to amalgamate the two sets of requirements to some extent. However newmat is definitely oriented towards the matrix library set.

5.3 Design questions

next - skip - up - start

Even within the bounds set by the requirements of a matrix library there is a substantial opportunity for variation between what different matrix packages might provide. It is not possible to build a matrix package that will meet everyone's requirements. In many cases if you put in one facility, you impose overheads on everyone using the package. This both in storage required for the program and in efficiency. Likewise a package that is optimised towards handling large matrices is likely to become less efficient for very small matrices where the administration time for the matrix may become significant compared with the time to carry out the operations. It is better to provide a variety of packages (hopefully compatible) so that most users can find one that meets their requirements. This package is intended to be one of these packages; but not all of them.

Since my background is in statistical methods, this package is oriented towards the kinds things you need for statistical analyses.

Now looking at some specific questions.

What size of matrices?

A matrix library may target small matrices (say 3 x 3), or medium sized matrices, or very large matrices.

A library targeting very small matrices will seek to minimise administration. A library for medium sized or very large matrices can spend more time on administration in order to conserve space or optimise the evaluation of expressions. A library for very large matrices will need to pay special attention to storage and numerical properties. This library is designed for medium sized matrices. This means it is worth introducing some optimisations, but I don't have to worry about setting up some form of virtual memory.

Which matrix types?

As well as the usual rectangular matrices, matrices occurring repeatedly in numerical calculations are upper and lower triangular matrices, symmetric matrices and diagonal matrices. This is particularly the case in calculations involving least squares and eigenvalue calculations. So as a first stage these were the types I decided to include.

It is also necessary to have types row vector and column vector. In a matrix package, in contrast to an array package, it is necessary to have both these types since they behave differently in matrix expressions. The vector types can be derived for the rectangular matrix type, so having them does not greatly increase the complexity of the package.

The problem with having several matrix types is the number of versions of the binary operators one needs. If one has 5 distinct matrix types then a simple library will need 25 versions of each of the binary operators. In fact, we can evade this problem, but at the cost of some complexity.

What element types?

Ideally we would allow element types double, float, complex and int, at least. It might be reasonably easy, using templates or equivalent, to provide a library which could handle a variety of element types. However, as soon as one starts implementing the binary operators between matrices with different element types, again one gets an explosion in the number of operations one needs to consider. At the present time the compilers I deal with are not up to handling this problem with templates. (Of course, when I started writing newmat there were no templates). But even when the compilers do meet the specifications of the draft standard, writing a matrix package that allows for a variety of element types using the template mechanism is going to be very difficult. I am inclined to use templates in an array library but not in a matrix library.

Hence I decided to implement only one element type. But the user can decide whether this is float or double. The package assumes elements are of type Real. The user typedefs Real to float or double.

It might also be worth including symmetric and triangular matrices with extra precision elements (double or long double) to be used for storage only and with a minimum of operations defined. These would be used for accumulating the results of sums of squares and product matrices or multi-stage QR triangularisations.

Allow matrix expressions

I want to be able to write matrix expressions the way I would on paper. So if I want to multiply two matrices and then add the transpose of a third one I can write something like X = A * B + C.t();. I want this expression to be evaluated with close to the same efficiency as a hand-coded version. This is not so much of a problem with expressions including a multiply since the multiply will dominate the time. However, it is not so easy to achieve with expressions with just + and -.

A second requirement is that temporary matrices generated during the evaluation of an expression are destroyed as quickly as possible.

A desirable feature is that a certain amount of intelligence be displayed in the evaluation of an expression. For example, in the expression X = A.i() * B; where i() denotes inverse, it would be desirable if the inverse wasn't explicitly calculated.

Naming convention

How are classes and public member functions to be named? As a general rule I have spelt identifiers out in full with individual words being capitalised. For example UpperTriangularMatrix. If you don't like this you can #define or typedef shorter names. This convention means you can select an abbreviation scheme that makes sense to you.

Exceptions to the general rule are the functions for transpose and inverse. To make matrix expressions more like the corresponding mathematical formulae, I have used the single letter abbreviations, t() and i().

Row and column index ranges

In mathematical work matrix subscripts usually start at one. In C, array subscripts start at zero. In Fortran, they start at one. Possibilities for this package were to make them start at 0 or 1 or be arbitrary.

Alternatively one could specify an index set for indexing the rows and columns of a matrix. One would be able to add or multiply matrices only if the appropriate row and column index sets were identical.

In fact, I adopted the simpler convention of making the rows and columns of a matrix be indexed by an integer starting at one, following the traditional convention. In an earlier version of the package I had them starting at zero, but even I was getting mixed up when trying to use this earlier package. So I reverted to the more usual notation and started at 1.

Element access - method and checking

We want to be able to use the notation A(i,j) to specify the (i,j)-th element of a matrix. This is the way mathematicians expect to address the elements of matrices. I consider the notation A[i][j] totally alien. However I include this as an option to help people converting from C.

There are two ways of working out the address of A(i,j). One is using a dope vector which contains the first address of each row. Alternatively you can calculate the address using the formula appropriate for the structure of A. I use this second approach. It is probably slower, but saves worrying about an extra bit of storage.

The other question is whether to check for i and j being in range. I do carry out this check following years of experience with both systems that do and systems that don't do this check. I would hope that the routines I supply with this package will reduce your need to access elements of matrices so speed of access is not a high priority.

Use iterators

Iterators are an alternative way of providing fast access to the elements of an array or matrix when they are to be accessed sequentially. They need to be customised for each type of matrix. I have not implemented iterators in this package, although some iterator like functions are used internally for some row and column functions.

5.4 Data storage

next - skip - up - start

The stack and heap

To understand how newmat stores matrices you need to know a little bit about the heap and stack.

The data values of variables or objects in a C++ program are stored in either of two sections of memory called the stack and the heap. Sometimes there is more than one heap to cater for different sized variables.

If you declare an automatic variable

   int x;

then the value of x is stored on the stack. As you declare more variables the stack gets bigger. When you exit a block (i.e a section of code delimited by curly brackets {...}) the memory used by the automatic variables declared in the block is released and the stack shrinks.

When you declare a variable with new, for example,

   int* y = new int;

the pointer y is stored on the stack but the value it is pointing to is stored on the heap. Memory on the heap is not released until the program explicitly does this with a delete statement

   delete *y;

or the program exits.

On the stack, variables and objects are is always added to the end of the stack and are removed in the reverse order to that in which they are added - that is the last on will be the first off. This is not the case with the heap, where the variables and objects can be removed in any order. So one can get alternating pieces of used and unused memory. When a new variable or object is declared on the heap the system needs to search for piece of unused memory large enough to hold it. This means that storing on the heap will usually be a slower process than storing on the stack. There is also likely to be waste space on the heap because of gaps between the used blocks of memory that are too small for the next object you want to store on the heap. There is also the possibility of wasting space if you forget to remove a variable or object on the heap even though you have finished using it. However, the stack is usually limited to holding small objects with size known at compile time. Large objects, objects whose size you don't know at compile time, and objects that you want to persist after the end of the block need to be stored on the heap.

In C++, the constructor/destructor system enables one to build complicated objects such as matrices that behave as automatic variables stored on the stack, so the programmer doesn't have to worry about deleting them at the end of the block, but which really utilise the heap for storing their data.

Structure of matrix objects

Each matrix object contains the basic information such as the number of rows and columns, the amount of memory used, a status variable and a pointer to the data array which is on the heap. So if you declare a matrix

   Matrix A(1000,1000);

there is an small amount of memory used on the stack for storing the numbers of rows and columns, the amount of  memory used, the status variable and the pointer together with 1,000,000 Real locations stored on the heap. When you exit the block in which A is declared, the heap memory used by A is automatically returned to the system, as well as the memory used on the stack.

Of course, if you use new to declare a matrix

   Matrix* B = new Matrix(1000,1000);

both the information about the size and the actual data are stored on heap and not deleted until the program exits or you do an explicit delete:

   delete *B;

If you carry out an assignment with = or << or do a resize() the data array currently associated with a matrix is destroyed and a new array generated. For example

   Matrix A(1000,1000);
   Matrix B(50, 50);
   ... put some values in B
   A = B;

At the last step the heap memory associated with A is returned to the system and a new block of heap memory is assigned to contain the new values. This happens even if there is no change in the amount of memory required.

One block or several

The elements of the matrix are stored as a single array. Alternatives would have been to store each row as a separate array or a set of adjacent rows as a separate array. The present solution simplifies the program but limits the size of matrices in 16 bit PCs that have a 64k byte limit on the size of arrays (I don't use the huge keyword). The large arrays may also cause problems for memory management in smaller machines. [The 16 bit PC problem has largely gone away but it was a problem when much of newmat was written. Now, occasionally I run into the 32 bit PC problem.]

By row or by column or other

In Fortran two dimensional arrays are stored by column. In most other systems they are stored by row. I have followed this later convention. This makes it easier to interface with other packages written in C but harder to interface with those written in Fortran. This may have been a wrong decision. Most work on the efficient manipulation of large matrices is being done in Fortran. It would have been easier to use this work if I had adopted the Fortran convention.

An alternative would be to store the elements by mid-sized rectangular blocks. This might impose less strain on memory management when one needs to access both rows and columns.

Storage of symmetric matrices

Symmetric matrices are stored as lower triangular matrices. The decision was pretty arbitrary, but it does slightly simplify the Cholesky decomposition program.

5.5 Memory management - reference counting or status variable?

next - skip - up - start

Consider the instruction

   X = A + B + C;

To evaluate this a simple program will add A to B putting the total in a temporary T1. Then it will add T1 to C creating another temporary T2 which will be copied into X. T1 and T2 will sit around till the end of the execution of the statement and perhaps of the block. It would be faster if the program recognised that T1 was temporary and stored the sum of T1 and C back into T1 instead of creating T2 and then avoided the final copy by just assigning the contents of T1 to X rather than copying. In this case there will be no temporaries requiring deletion. (More precisely there will be a header to be deleted but no contents).

For an instruction like

   X = (A * B) + (C * D);

we can't easily avoid one temporary being left over, so we would like this temporary deleted as quickly as possible.

I provide the functionality for doing all this by attaching a status variable to each matrix. This indicates if the matrix is temporary so that its memory is available for recycling or deleting. Any matrix operation checks the status variables of the matrices it is working with and recycles or deletes any temporary memory.

An alternative or additional approach would be to use reference counting and delayed copying - also known as copy on write. If a program requests a matrix to be copied, the copy is delayed until an instruction is executed which modifies the memory of either the original matrix or the copy. If the original matrix is deleted before either matrix is modified, in effect, the values of the original matrix are transferred to the copy without any actual copying taking place. This solves the difficult problem of returning an object from a function without copying and saves the unnecessary copying in the previous examples.

There are downsides to the delayed copying approach. Typically, for delayed copying one uses a structure like the following:

   Matrix
     |
     +------> Array Object
     |          |
     |          +------> Data array
     |          |
     |          +------- Counter
     |
     +------ Dimension information

where the arrows denote a pointer to a data structure. If one wants to access the Data array one will need to track through two pointers. If one is going to write, one will have to check whether one needs to copy first. This is not important when one is going to access the whole array, say, for a add operation. But if one wants to access just a single element, then it imposes a significant additional overhead on that operation. Any subscript operation would need to check whether an update was required - even read since it is hard for the compiler to tell whether a subscript access is a read or write.

Some matrix libraries don't bother to do this. So if you write A = B; and then modify an element of one of A or B, then the same element of the other is also modified. I don't think this is acceptable behaviour.

Delayed copy does not provide the additional functionality of my approach but I suppose it would be possible to have both delayed copy and tagging temporaries.

My approach does not automatically avoid all copying. In particular, you need use a special technique to return a matrix from a function without copying.

5.6 Memory management - accessing contiguous locations

next - skip - up - start

Modern computers work faster if one accesses memory by running through contiguous locations rather than by jumping around all over the place. Newmat stores matrices by rows so that algorithms that access memory by running along rows will tend to work faster than one that runs down columns. A number of the algorithms used in Newmat were developed before this was an issue and so are not as efficient as possible.

I have gradually upgrading the algorithms to access memory by rows. The following table shows the current status of this process.

Function Contiguous memory access Comment
Add, subtract Yes  
Multiply Yes  
Concatenate Yes  
Transpose No  
Invert and solve Yes Mostly
Cholesky Yes  
QRZ, QRZT Yes  
SVD No  
Jacobi No Not an issue; used only for smaller matrices
Eigenvalues No  
Sort Yes Quick-sort is naturally good
FFT ? Could be improved?

5.7 Evaluation of expressions - lazy evaluation

next - skip - up - start

Consider the instruction

   X = B - X;

A simple program will subtract X from B, store the result in a temporary T1 and copy T1 into X. It would be faster if the program recognised that the result could be stored directly into X. This would happen automatically if the program could look at the instruction first and mark X as temporary.

C programmers would expect to avoid the same problem with

   X = X - B;

by using an operator -=

   X -= B;

However this is an unnatural notation for non C users and it may be nicer to write X = X - B; and know that the program will carry out the simplification.

Another example where this intelligent analysis of an instruction is helpful is in

   X = A.i() * B;

where i() denotes inverse. Numerical analysts know it is inefficient to evaluate this expression by carrying out the inverse operation and then the multiply. Yet it is a convenient way of writing the instruction. It would be helpful if the program recognised this expression and carried out the more appropriate approach.

I regard this interpretation of A.i() * B as just providing a convenient notation. The objective is not primarily to correct the errors of people who are unaware of the inefficiency of A.i() * B if interpreted literally.

There is a third reason for the two-stage evaluation of expressions and this is probably the most important one. In C++ it is quite hard to return an expression from a function such as (*, + etc) without a copy. This is particularly the case when an assignment (=) is involved. The mechanism described here provides one way for avoiding this in matrix expressions.

The C++ standard (section 12.8/15) allows the compiler to optimise away the copy when returning an object from a function (but there will still be one copy is an assignment (=) is involved). This means special handling of returns from a function is less important when a modern optimising compiler is being used. 

To carry out this intelligent analysis of an instruction matrix expressions are evaluated in two stages. In the the first stage a tree representation of the expression is formed. For example (A+B)*C is represented by a tree


       *
      / \
     +   C
    / \
   A   B

Rather than adding A and B the + operator yields an object of a class AddedMatrix which is just a pair of pointers to A and B. Then the * operator yields a MultipliedMatrix which is a pair of pointers to the AddedMatrix and C. The tree is examined for any simplifications and then evaluated recursively.

Further possibilities not yet included are to recognise A.t()*A and A.t()+A as symmetric or to improve the efficiency of evaluation of expressions like A+B+C, A*B*C, A*B.t() (t() denotes transpose).

One of the disadvantages of the two-stage approach is that the types of matrix expressions are determined at run-time. So the compiler will not detect errors of the type

   Matrix M;
   DiagonalMatrix D;
   ....;
   D = M;

We don't allow conversions using = when information would be lost. Such errors will be detected when the statement is executed.

5.8 How to overcome an explosion in number of operations

next - skip - up - start

The package attempts to solve the problem of the large number of versions of the binary operations required when one has a variety of types.

With n types of matrices the binary operations will each require n-squared separate algorithms. Some reduction in the number may be possible by carrying out conversions. However, the situation rapidly becomes impossible with more than 4 or 5 types. Doug Lea told me that it was possible to avoid this problem. I don't know what his solution is. Here's mine.

Each matrix type includes routines for extracting individual rows or columns. I assume a row or column consists of a sequence of zeros, a sequence of stored values and then another sequence of zeros. Only a single algorithm is then required for each binary operation. The rows can be located very quickly since most of the matrices are stored row by row. Columns must be copied and so the access is somewhat slower. As far as possible my algorithms access the matrices by row.

There is another approach. Each of the matrix types defined in this package can be set up so both rows and columns have their elements at equal intervals provided we are prepared to store the rows and columns in up to three chunks. With such an approach one could write a single "generic" algorithm for each of multiply and add. This would be a reasonable alternative to my approach.

I provide several algorithms for operations like + . If one is adding two matrices of the same type then there is no need to access the individual rows or columns and a faster general algorithm is appropriate.

Generally the method works well. However symmetric matrices are not always handled very efficiently (yet) since complete rows are not stored explicitly.

The original version of the package did not use this access by row or column method and provided the multitude of algorithms for the combination of different matrix types. The code file length turned out to be just a little longer than the present one when providing the same facilities with 5 distinct types of matrices. It would have been very difficult to increase the number of matrix types in the original version. Apparently 4 to 5 types is about the break even point for switching to the approach adopted in the present package.

However it must also be admitted that there is a substantial overhead in the approach adopted in the present package for small matrices. The test program developed for the original version of the package takes 30 to 50% longer to run with the current version (though there may be some other reasons for this). This is for matrices in the range 6x6 to 10x10.

To try to improve the situation a little I do provide an ordinary matrix multiplication routine for the case when all the matrices involved are rectangular.

5.9 Destruction of temporaries

next - skip - up - start

Versions before version 5 of newmat did not work correctly with Gnu C++ (version 5 or earlier). This was because the tree structure used to represent a matrix expression was set up on the stack. This was fine for AT&T, Borland and Zortech C++.

However early version Gnu C++ destroys temporary structures as soon as the function that accesses them finishes. The other compilers wait until the end of the current expression or current block. To overcome this problem, there is now an option to store the temporaries forming the tree structure on the heap (created with new) and to delete them explicitly. Activate the definition of TEMPS_DESTROYED_QUICKLY to set this option.

Now that the C++ standards committee has said that temporary structures should not be destroyed before a statement finishes, I suggest using the stack, because of the difficulty of managing exceptions with the heap version.

5.10 A calculus of matrix types

next - skip - up - start

The program needs to be able to work out the class of the result of a matrix expression. This is to check that a conversion is legal or to determine the class of an intermediate result. To assist with this, a class MatrixType is defined. Operators +, -, *, >= are defined to calculate the types of the results of expressions or to check that conversions are legal.

Early versions of newmat stored the types of the results of operations in a table. So, for example, if you multiplied an UpperTriangularMatrix by a LowerTriangularMatrix, newmat would look up the table and see that the result was of type Matrix. With this approach the exploding number of operations problem recurred although not as seriously as when code had to be written for each pair of types. But there was always the suspicion that somewhere, there was an error in one of those 9x9 tables, that would be very hard to find. And the problem would get worse as additional matrix types or operators were included.

The present version of newmat solves the problem by assigning attributes such as diagonal or band or upper triangular to each matrix type. Which attributes a matrix type has, is stored as bits in an integer. As an example, the DiagonalMatrix type has the bits corresponding to diagonal, symmetric and band equal to 1. By looking at the attributes of each of the operands of a binary operator, the program can work out the attributes of the result of the operation with simple bitwise operations. Hence it can deduce an appropriate type. The symmetric attribute is a minor problem because symmetric * symmetric does not yield symmetric unless both operands are diagonal. But otherwise very simple code can be used to deduce the attributes of the result of a binary operation.

Tables of the types resulting from the binary operators are output at the beginning of the test program.

5.11 Pointer arithmetic

next - skip - up - start

Suppose you do something like

   int* y = new int[100];
   y += 200;          // y points to something outside the array
   // y is never accessed

Then the standard says that the behaviour of the program is undefined even if y is never accessed. (You are allowed to calculate a pointer value one location beyond the end of the array). In practice, a program like this does not cause any problems with any compiler I have come across and no-one has reported any such problems to me.

However, this error is detected by Borland's Code Guard bound's checker and this makes it very difficult to use this to use Code Guard to detect other problems since the output is swamped by reports of this error.

Now consider

   int* y = new int[100];
   y += 200;          // y points to something outside the array
   y -= 150;          // y points to something inside the array
   // y is accessed

Again this is not strictly correct but does not seem to cause a problem. But it is much more doubtful than the previous example.

I removed most instances of the second version of the problem from Newmat09. Hopefully the remainder of these instances were removed from the current version of Newmat10. In addition, most instances of the first version of the problem have also been fixed.

There is one exception. The interface to the Numerical Recipes in C does still contain the second version of the problem. This is inevitable because of the way Numerical Recipes in C stores vectors and matrices. If you are running the test program with a bounds checking program, edit tmt.h to disable the testing of the NRIC interface.

The rule does does cause a problem for authors of matrix and multidimensional array packages. If we want to run down a column of a matrix we would like to do something like

   // set values of column 1
   Matrix A;
   ... set dimensions and put values in A
   Real* a = A.Store();               // points to first element
   int nr = A.Nrows();                // number of rows
   int nc = A.Ncols();                // number of columns
   while (nr--)
   {
      *a = something to put in first element of row
      a += nc;                        // jump to next element of column
   }

If the matrix has more than one column the last execution of a += nc; will run off the end of the space allocated to the matrix and we'll get a bounds error report.

Instead we have to use a program like

   // set values of column 1
   Matrix A;
   ... set dimensions and put values in A
   Real* a = A.Store();               // points to first element
   int nr = A.Nrows();                // number of rows
   int nc = A.Ncols();                // number of columns
   if (nr != 0)
   {
      for(;;)
      {
         *a = something to put in first element of row
         if (!(--nr)) break;
         a += nc;                     // jump to next element of column
      }
   }

which is more complicated and consequently introduces more chance of error.

5.12 Error handling

next - skip - up - start

The library now does have a moderately graceful exit from errors. One can use either the simulated exceptions or the compiler supported exceptions. When newmat08 was released (in 1995), compiler exception handling in the compilers I had access to was unreliable. I recommended you used my simulated exceptions. In 1997 compiler supported exceptions seemed to work on a variety of compilers - but not all compilers. This is still true in 2001. Try using the compiler supported exceptions if you have a recent compiler, but if you are getting strange crashes or errors try going back to my simulated exceptions.

The approach in the present library, attempting to simulate C++ exceptions, is not completely satisfactory, but seems a good interim solution for those who cannot use compiler supported exceptions. People who don't want exceptions in any shape or form, can set the option to exit the program if an exception is thrown.

The exception mechanism cannot clean-up objects explicitly created by new. This must be explicitly carried out by the package writer or the package user. I have not yet done this completely with the present package so occasionally a little garbage may be left behind after an exception. I don't think this is a big problem, but it is one that needs fixing.

5.13 Sparse matrices

next - skip - up - start

The library does not support sparse matrices.

For sparse matrices there is going to be some kind of structure vector. It is going to have to be calculated for the results of expressions in much the same way that types are calculated. In addition, a whole new set of row and column operations would have to be written.

Sparse matrices are important for people solving large sets of differential equations as well as being important for statistical and operational research applications.

But there are packages being developed specifically for sparse matrices and these might present the best approach, at least where sparse matrices are the main interest.

5.14 Complex matrices

next - skip - up - start

The package does not yet support matrices with complex elements. There are at least two approaches to including these. One is to have matrices with complex elements.

This probably means making new versions of the basic row and column operations for Real*Complex, Complex*Complex, Complex*Real and similarly for + and -. This would be OK, except that if I also want to do this for sparse matrices, then when you put these together, the whole thing will get out of hand.

The alternative is to represent a Complex matrix by a pair of Real matrices. One probably needs another level of decoding expressions but I think it might still be simpler than the first approach. But there is going to be a problem with accessing elements and it does not seem possible to solve this in an entirely satisfactory way.

Complex matrices are used extensively by electrical engineers and physicists and really should be fully supported in a comprehensive package.

You can simulate most complex operations by representing Z = X + iY by

    /  X   Y \
    \ -Y   X / 

Most matrix operations will simulate the corresponding complex operation, when applied to this matrix. But, of course, this matrix is essentially twice as big as you would need with a genuine complex matrix library.

return to top
return to online documentation page

 

 

 

 

 

 

 

newmat-1.10.4/nm_b55.mak0000644001161000116100000001516510407125155013063 0ustar rzrrzrBORLANDPATH = "C:\program files\Borland\cbuilder5" TASM = TASM32 TLIB = tlib TLINK = ilink32 LIBPATH = $(BORLANDPATH)\LIB INCLUDEPATH = $(BORLANDPATH)\INCLUDE DIFF = sdiff PRE = CC = bcc32 -W- -v- -H- -3 -N -Og -Oi -Ov -f -I$(INCLUDEPATH) .cpp.obj: $(CC) -c {$< } everything: tmt.exe example.exe test_exc.exe nl_ex.exe sl_ex.exe garch.exe newmat_lobj = newmat1.obj newmat2.obj newmat3.obj newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj newmatex.obj bandmat.obj submat.obj myexcept.obj cholesky.obj evalue.obj fft.obj hholder.obj jacobi.obj newfft.obj sort.obj svd.obj newmatrm.obj newmat9.obj newmat.lib: $(newmat_lobj) $(TLIB) $@ /P32 /u $(newmat_lobj) tmt_obj = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmtm.obj tmt.exe: $(tmt_obj) newmat.lib $(TLINK) /x/L$(LIBPATH)/Gn -Tpe -ap -c @&&| c0x32.obj $(tmt_obj),$@,, newmat.lib import32.lib cw32.lib | example_obj = example.obj example.exe: $(example_obj) newmat.lib $(TLINK) /x/L$(LIBPATH)/Gn -Tpe -ap -c @&&| c0x32.obj $(example_obj),$@,, newmat.lib import32.lib cw32.lib | test_exc_obj = test_exc.obj test_exc.exe: $(test_exc_obj) newmat.lib $(TLINK) /x/L$(LIBPATH)/Gn -Tpe -ap -c @&&| c0x32.obj $(test_exc_obj),$@,, newmat.lib import32.lib cw32.lib | nl_ex_obj = nl_ex.obj newmatnl.obj nl_ex.exe: $(nl_ex_obj) newmat.lib $(TLINK) /x/L$(LIBPATH)/Gn -Tpe -ap -c @&&| c0x32.obj $(nl_ex_obj),$@,, newmat.lib import32.lib cw32.lib | sl_ex_obj = sl_ex.obj solution.obj myexcept.obj sl_ex.exe: $(sl_ex_obj) $(TLINK) /x/L$(LIBPATH)/Gn -Tpe -ap -c @&&| c0x32.obj $(sl_ex_obj),$@,,import32.lib cw32.lib | garch_obj = garch.obj newmatnl.obj garch.exe: $(garch_obj) newmat.lib $(TLINK) /x/L$(LIBPATH)/Gn -Tpe -ap -c @&&| c0x32.obj $(garch_obj),$@,, newmat.lib import32.lib cw32.lib | newmat1.obj: newmat1.cpp newmat.h include.h boolean.h myexcept.h newmat2.obj: newmat2.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat3.obj: newmat3.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat4.obj: newmat4.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat5.obj: newmat5.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat6.obj: newmat6.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat7.obj: newmat7.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat8.obj: newmat8.cpp include.h newmat.h newmatrc.h precisio.h boolean.h myexcept.h controlw.h newmatex.obj: newmatex.cpp include.h newmat.h boolean.h myexcept.h bandmat.obj: bandmat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h submat.obj: submat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h myexcept.obj: myexcept.cpp include.h myexcept.h cholesky.obj: cholesky.cpp include.h newmat.h boolean.h myexcept.h evalue.obj: evalue.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h fft.obj: fft.cpp include.h newmatap.h newmat.h boolean.h myexcept.h hholder.obj: hholder.cpp include.h newmatap.h newmat.h boolean.h myexcept.h jacobi.obj: jacobi.cpp include.h newmatap.h precisio.h newmatrm.h newmat.h boolean.h myexcept.h newfft.obj: newfft.cpp newmatap.h newmat.h include.h boolean.h myexcept.h sort.obj: sort.cpp include.h newmatap.h newmat.h boolean.h myexcept.h svd.obj: svd.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h newmatrm.obj: newmatrm.cpp newmat.h newmatrm.h include.h boolean.h myexcept.h newmat9.obj: newmat9.cpp include.h newmat.h newmatio.h newmatrc.h boolean.h myexcept.h controlw.h tmt.obj: tmt.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt1.obj: tmt1.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt2.obj: tmt2.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt3.obj: tmt3.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt4.obj: tmt4.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt5.obj: tmt5.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt6.obj: tmt6.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt7.obj: tmt7.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt8.obj: tmt8.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt9.obj: tmt9.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmta.obj: tmta.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtb.obj: tmtb.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtc.obj: tmtc.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtd.obj: tmtd.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmte.obj: tmte.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtf.obj: tmtf.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtg.obj: tmtg.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmth.obj: tmth.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmti.obj: tmti.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtj.obj: tmtj.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtk.obj: tmtk.cpp include.h newmatap.h newmatio.h tmt.h newmat.h boolean.h myexcept.h tmtl.obj: tmtl.cpp newmat.h tmt.h include.h boolean.h myexcept.h tmtm.obj: tmtm.cpp newmat.h tmt.h include.h boolean.h myexcept.h example.obj: example.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h test_exc.obj: test_exc.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h nl_ex.obj: nl_ex.cpp newmatnl.h newmatio.h newmat.h include.h boolean.h myexcept.h newmatnl.obj: newmatnl.cpp newmatap.h newmatnl.h newmat.h include.h boolean.h myexcept.h sl_ex.obj: sl_ex.cpp include.h solution.h boolean.h myexcept.h solution.obj: solution.cpp include.h boolean.h myexcept.h solution.h garch.obj: garch.cpp newmatap.h newmatio.h newmatnl.h newmat.h include.h boolean.h myexcept.h tmt.txx: tmt.exe $(PRE)tmt > tmt.txx $(DIFF) tmt.txt tmt.txx example.txx: example.exe $(PRE)example > example.txx $(DIFF) example.txt example.txx test_exc.txx: test_exc.exe $(PRE)test_exc > test_exc.txx $(DIFF) test_exc.txt test_exc.txx nl_ex.txx: nl_ex.exe $(PRE)nl_ex > nl_ex.txx $(DIFF) nl_ex.txt nl_ex.txx sl_ex.txx: sl_ex.exe $(PRE)sl_ex > sl_ex.txx $(DIFF) sl_ex.txt sl_ex.txx garch.txx: garch.exe $(PRE)garch > garch.txx $(DIFF) garch.txt garch.txx newmat-1.10.4/nm_cc.mak0000644001161000116100000001400210407125235013041 0ustar rzrrzrCXX = CC CXXFLAGS = -O2 DIFF = ./sdiff PRE = ./ .SUFFIXES: .SUFFIXES: .a .o .c .cpp .cpp.o: rm -f $*.cxx ln $*.cpp $*.cxx $(CXX) $(CXXFLAGS) -c $*.cxx rm $*.cxx everything: tmt example test_exc nl_ex sl_ex garch newmat_lobj = newmat1.o newmat2.o newmat3.o newmat4.o newmat5.o newmat6.o newmat7.o newmat8.o newmatex.o bandmat.o submat.o myexcept.o cholesky.o evalue.o fft.o hholder.o jacobi.o newfft.o sort.o svd.o newmatrm.o newmat9.o libnewmat.a: $(newmat_lobj) $(AR) -cr $@ $(newmat_lobj) ranlib $@ tmt_obj = tmt.o tmt1.o tmt2.o tmt3.o tmt4.o tmt5.o tmt6.o tmt7.o tmt8.o tmt9.o tmta.o tmtb.o tmtc.o tmtd.o tmte.o tmtf.o tmtg.o tmth.o tmti.o tmtj.o tmtk.o tmtl.o tmtm.o tmt: $(tmt_obj) libnewmat.a $(CXX) -o $@ $(tmt_obj) -L. -lnewmat -lm example_obj = example.o example: $(example_obj) libnewmat.a $(CXX) -o $@ $(example_obj) -L. -lnewmat -lm test_exc_obj = test_exc.o test_exc: $(test_exc_obj) libnewmat.a $(CXX) -o $@ $(test_exc_obj) -L. -lnewmat -lm nl_ex_obj = nl_ex.o newmatnl.o nl_ex: $(nl_ex_obj) libnewmat.a $(CXX) -o $@ $(nl_ex_obj) -L. -lnewmat -lm sl_ex_obj = sl_ex.o solution.o myexcept.o sl_ex: $(sl_ex_obj) $(CXX) -o $@ $(sl_ex_obj) -L. -lm garch_obj = garch.o newmatnl.o garch: $(garch_obj) libnewmat.a $(CXX) -o $@ $(garch_obj) -L. -lnewmat -lm newmat1.o: newmat1.cpp newmat.h include.h boolean.h myexcept.h newmat2.o: newmat2.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat3.o: newmat3.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat4.o: newmat4.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat5.o: newmat5.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat6.o: newmat6.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat7.o: newmat7.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat8.o: newmat8.cpp include.h newmat.h newmatrc.h precisio.h boolean.h myexcept.h controlw.h newmatex.o: newmatex.cpp include.h newmat.h boolean.h myexcept.h bandmat.o: bandmat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h submat.o: submat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h myexcept.o: myexcept.cpp include.h myexcept.h cholesky.o: cholesky.cpp include.h newmat.h boolean.h myexcept.h evalue.o: evalue.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h fft.o: fft.cpp include.h newmatap.h newmat.h boolean.h myexcept.h hholder.o: hholder.cpp include.h newmatap.h newmat.h boolean.h myexcept.h jacobi.o: jacobi.cpp include.h newmatap.h precisio.h newmatrm.h newmat.h boolean.h myexcept.h newfft.o: newfft.cpp newmatap.h newmat.h include.h boolean.h myexcept.h sort.o: sort.cpp include.h newmatap.h newmat.h boolean.h myexcept.h svd.o: svd.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h newmatrm.o: newmatrm.cpp newmat.h newmatrm.h include.h boolean.h myexcept.h newmat9.o: newmat9.cpp include.h newmat.h newmatio.h newmatrc.h boolean.h myexcept.h controlw.h tmt.o: tmt.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt1.o: tmt1.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt2.o: tmt2.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt3.o: tmt3.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt4.o: tmt4.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt5.o: tmt5.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt6.o: tmt6.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt7.o: tmt7.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt8.o: tmt8.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt9.o: tmt9.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmta.o: tmta.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtb.o: tmtb.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtc.o: tmtc.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtd.o: tmtd.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmte.o: tmte.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtf.o: tmtf.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtg.o: tmtg.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmth.o: tmth.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmti.o: tmti.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtj.o: tmtj.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtk.o: tmtk.cpp include.h newmatap.h newmatio.h tmt.h newmat.h boolean.h myexcept.h tmtl.o: tmtl.cpp newmat.h tmt.h include.h boolean.h myexcept.h tmtm.o: tmtm.cpp newmat.h tmt.h include.h boolean.h myexcept.h example.o: example.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h test_exc.o: test_exc.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h nl_ex.o: nl_ex.cpp newmatnl.h newmatio.h newmat.h include.h boolean.h myexcept.h newmatnl.o: newmatnl.cpp newmatap.h newmatnl.h newmat.h include.h boolean.h myexcept.h sl_ex.o: sl_ex.cpp include.h solution.h boolean.h myexcept.h solution.o: solution.cpp include.h boolean.h myexcept.h solution.h garch.o: garch.cpp newmatap.h newmatio.h newmatnl.h newmat.h include.h boolean.h myexcept.h tmt.txx: tmt $(PRE)tmt > tmt.txx $(DIFF) tmt.txt tmt.txx example.txx: example $(PRE)example > example.txx $(DIFF) example.txt example.txx test_exc.txx: test_exc $(PRE)test_exc > test_exc.txx $(DIFF) test_exc.txt test_exc.txx nl_ex.txx: nl_ex $(PRE)nl_ex > nl_ex.txx $(DIFF) nl_ex.txt nl_ex.txx sl_ex.txx: sl_ex $(PRE)sl_ex > sl_ex.txx $(DIFF) sl_ex.txt sl_ex.txx garch.txx: garch $(PRE)garch > garch.txx $(DIFF) garch.txt garch.txx newmat-1.10.4/nm_gnu.mak0000644001161000116100000001372310407125226013256 0ustar rzrrzrCXX = g++ CXXFLAGS = -O2 -Wall DIFF = ./sdiff PRE = ./ MAJOR = 1 MINOR = 0 %.o: %.cpp $(CXX) $(CXXFLAGS) -c $*.cpp everything: tmt example test_exc nl_ex sl_ex garch newmat_lobj = newmat1.o newmat2.o newmat3.o newmat4.o newmat5.o newmat6.o newmat7.o newmat8.o newmatex.o bandmat.o submat.o myexcept.o cholesky.o evalue.o fft.o hholder.o jacobi.o newfft.o sort.o svd.o newmatrm.o newmat9.o libnewmat.a: $(newmat_lobj) $(AR) -cr $@ $(newmat_lobj) ranlib $@ tmt_obj = tmt.o tmt1.o tmt2.o tmt3.o tmt4.o tmt5.o tmt6.o tmt7.o tmt8.o tmt9.o tmta.o tmtb.o tmtc.o tmtd.o tmte.o tmtf.o tmtg.o tmth.o tmti.o tmtj.o tmtk.o tmtl.o tmtm.o tmt: $(tmt_obj) libnewmat.a $(CXX) -o $@ $(tmt_obj) -L. -lnewmat -lm example_obj = example.o example: $(example_obj) libnewmat.a $(CXX) -o $@ $(example_obj) -L. -lnewmat -lm test_exc_obj = test_exc.o test_exc: $(test_exc_obj) libnewmat.a $(CXX) -o $@ $(test_exc_obj) -L. -lnewmat -lm nl_ex_obj = nl_ex.o newmatnl.o nl_ex: $(nl_ex_obj) libnewmat.a $(CXX) -o $@ $(nl_ex_obj) -L. -lnewmat -lm sl_ex_obj = sl_ex.o solution.o myexcept.o sl_ex: $(sl_ex_obj) $(CXX) -o $@ $(sl_ex_obj) -L. -lm garch_obj = garch.o newmatnl.o garch: $(garch_obj) libnewmat.a $(CXX) -o $@ $(garch_obj) -L. -lnewmat -lm newmat1.o: newmat1.cpp newmat.h include.h boolean.h myexcept.h newmat2.o: newmat2.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat3.o: newmat3.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat4.o: newmat4.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat5.o: newmat5.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat6.o: newmat6.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat7.o: newmat7.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat8.o: newmat8.cpp include.h newmat.h newmatrc.h precisio.h boolean.h myexcept.h controlw.h newmatex.o: newmatex.cpp include.h newmat.h boolean.h myexcept.h bandmat.o: bandmat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h submat.o: submat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h myexcept.o: myexcept.cpp include.h myexcept.h cholesky.o: cholesky.cpp include.h newmat.h boolean.h myexcept.h evalue.o: evalue.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h fft.o: fft.cpp include.h newmatap.h newmat.h boolean.h myexcept.h hholder.o: hholder.cpp include.h newmatap.h newmat.h boolean.h myexcept.h jacobi.o: jacobi.cpp include.h newmatap.h precisio.h newmatrm.h newmat.h boolean.h myexcept.h newfft.o: newfft.cpp newmatap.h newmat.h include.h boolean.h myexcept.h sort.o: sort.cpp include.h newmatap.h newmat.h boolean.h myexcept.h svd.o: svd.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h newmatrm.o: newmatrm.cpp newmat.h newmatrm.h include.h boolean.h myexcept.h newmat9.o: newmat9.cpp include.h newmat.h newmatio.h newmatrc.h boolean.h myexcept.h controlw.h tmt.o: tmt.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt1.o: tmt1.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt2.o: tmt2.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt3.o: tmt3.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt4.o: tmt4.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt5.o: tmt5.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt6.o: tmt6.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt7.o: tmt7.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt8.o: tmt8.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt9.o: tmt9.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmta.o: tmta.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtb.o: tmtb.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtc.o: tmtc.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtd.o: tmtd.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmte.o: tmte.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtf.o: tmtf.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtg.o: tmtg.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmth.o: tmth.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmti.o: tmti.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtj.o: tmtj.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtk.o: tmtk.cpp include.h newmatap.h newmatio.h tmt.h newmat.h boolean.h myexcept.h tmtl.o: tmtl.cpp newmat.h tmt.h include.h boolean.h myexcept.h tmtm.o: tmtm.cpp newmat.h tmt.h include.h boolean.h myexcept.h example.o: example.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h test_exc.o: test_exc.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h nl_ex.o: nl_ex.cpp newmatnl.h newmatio.h newmat.h include.h boolean.h myexcept.h newmatnl.o: newmatnl.cpp newmatap.h newmatnl.h newmat.h include.h boolean.h myexcept.h sl_ex.o: sl_ex.cpp include.h solution.h boolean.h myexcept.h solution.o: solution.cpp include.h boolean.h myexcept.h solution.h garch.o: garch.cpp newmatap.h newmatio.h newmatnl.h newmat.h include.h boolean.h myexcept.h tmt.txx: tmt $(PRE)tmt > tmt.txx $(DIFF) tmt.txt tmt.txx example.txx: example $(PRE)example > example.txx $(DIFF) example.txt example.txx test_exc.txx: test_exc $(PRE)test_exc > test_exc.txx $(DIFF) test_exc.txt test_exc.txx nl_ex.txx: nl_ex $(PRE)nl_ex > nl_ex.txx $(DIFF) nl_ex.txt nl_ex.txx sl_ex.txx: sl_ex $(PRE)sl_ex > sl_ex.txx $(DIFF) sl_ex.txt sl_ex.txx garch.txx: garch $(PRE)garch > garch.txx $(DIFF) garch.txt garch.txx newmat-1.10.4/nm_i8.mak0000644001161000116100000001422310407125214012776 0ustar rzrrzr conlibs = libm.lib libc.lib DIFF = sdiff PRE = .SUFFIXES: .cpp .cpp.obj: icl -c -GX -GR -Ge -GS -Qpc80 -Qprec -Qprec_div -nologo -Qlong_double $*.cpp everything: tmt.exe example.exe test_exc.exe nl_ex.exe sl_ex.exe garch.exe newmat_lobj = newmat1.obj newmat2.obj newmat3.obj newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj newmatex.obj bandmat.obj submat.obj myexcept.obj cholesky.obj evalue.obj fft.obj hholder.obj jacobi.obj newfft.obj sort.obj svd.obj newmatrm.obj newmat9.obj newmat.lib: $(newmat_lobj) lib -Out:$@ $(newmat_lobj) tmt_obj = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmtm.obj tmt.exe: $(tmt_obj) newmat.lib link -Out:$@ $(conlibs) $(tmt_obj) newmat.lib example_obj = example.obj example.exe: $(example_obj) newmat.lib link -Out:$@ $(conlibs) $(example_obj) newmat.lib test_exc_obj = test_exc.obj test_exc.exe: $(test_exc_obj) newmat.lib link -Out:$@ $(conlibs) $(test_exc_obj) newmat.lib nl_ex_obj = nl_ex.obj newmatnl.obj nl_ex.exe: $(nl_ex_obj) newmat.lib link -Out:$@ $(conlibs) $(nl_ex_obj) newmat.lib sl_ex_obj = sl_ex.obj solution.obj myexcept.obj sl_ex.exe: $(sl_ex_obj) link -Out:$@ $(conlibs) $(sl_ex_obj) garch_obj = garch.obj newmatnl.obj garch.exe: $(garch_obj) newmat.lib link -Out:$@ $(conlibs) $(garch_obj) newmat.lib newmat1.obj: newmat1.cpp newmat.h include.h boolean.h myexcept.h newmat2.obj: newmat2.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat3.obj: newmat3.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat4.obj: newmat4.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat5.obj: newmat5.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat6.obj: newmat6.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat7.obj: newmat7.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat8.obj: newmat8.cpp include.h newmat.h newmatrc.h precisio.h boolean.h myexcept.h controlw.h newmatex.obj: newmatex.cpp include.h newmat.h boolean.h myexcept.h bandmat.obj: bandmat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h submat.obj: submat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h myexcept.obj: myexcept.cpp include.h myexcept.h cholesky.obj: cholesky.cpp include.h newmat.h boolean.h myexcept.h evalue.obj: evalue.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h fft.obj: fft.cpp include.h newmatap.h newmat.h boolean.h myexcept.h hholder.obj: hholder.cpp include.h newmatap.h newmat.h boolean.h myexcept.h jacobi.obj: jacobi.cpp include.h newmatap.h precisio.h newmatrm.h newmat.h boolean.h myexcept.h newfft.obj: newfft.cpp newmatap.h newmat.h include.h boolean.h myexcept.h sort.obj: sort.cpp include.h newmatap.h newmat.h boolean.h myexcept.h svd.obj: svd.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h newmatrm.obj: newmatrm.cpp newmat.h newmatrm.h include.h boolean.h myexcept.h newmat9.obj: newmat9.cpp include.h newmat.h newmatio.h newmatrc.h boolean.h myexcept.h controlw.h tmt.obj: tmt.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt1.obj: tmt1.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt2.obj: tmt2.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt3.obj: tmt3.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt4.obj: tmt4.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt5.obj: tmt5.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt6.obj: tmt6.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt7.obj: tmt7.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt8.obj: tmt8.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt9.obj: tmt9.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmta.obj: tmta.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtb.obj: tmtb.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtc.obj: tmtc.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtd.obj: tmtd.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmte.obj: tmte.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtf.obj: tmtf.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtg.obj: tmtg.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmth.obj: tmth.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmti.obj: tmti.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtj.obj: tmtj.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtk.obj: tmtk.cpp include.h newmatap.h newmatio.h tmt.h newmat.h boolean.h myexcept.h tmtl.obj: tmtl.cpp newmat.h tmt.h include.h boolean.h myexcept.h tmtm.obj: tmtm.cpp newmat.h tmt.h include.h boolean.h myexcept.h example.obj: example.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h test_exc.obj: test_exc.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h nl_ex.obj: nl_ex.cpp newmatnl.h newmatio.h newmat.h include.h boolean.h myexcept.h newmatnl.obj: newmatnl.cpp newmatap.h newmatnl.h newmat.h include.h boolean.h myexcept.h sl_ex.obj: sl_ex.cpp include.h solution.h boolean.h myexcept.h solution.obj: solution.cpp include.h boolean.h myexcept.h solution.h garch.obj: garch.cpp newmatap.h newmatio.h newmatnl.h newmat.h include.h boolean.h myexcept.h tmt.txx: tmt.exe $(PRE)tmt > tmt.txx $(DIFF) tmt.txt tmt.txx example.txx: example.exe $(PRE)example > example.txx $(DIFF) example.txt example.txx test_exc.txx: test_exc.exe $(PRE)test_exc > test_exc.txx $(DIFF) test_exc.txt test_exc.txx nl_ex.txx: nl_ex.exe $(PRE)nl_ex > nl_ex.txx $(DIFF) nl_ex.txt nl_ex.txx sl_ex.txx: sl_ex.exe $(PRE)sl_ex > sl_ex.txx $(DIFF) sl_ex.txt sl_ex.txx garch.txx: garch.exe $(PRE)garch > garch.txx $(DIFF) garch.txt garch.txx newmat-1.10.4/nm_il8.mak0000644001161000116100000001376110407125217013163 0ustar rzrrzrCXX = icpc CXXFLAGS = -O2 -mp -prec_div -pc80 -long_double DIFF = ./sdiff PRE = ./ MAJOR = 101 MINOR = 0 %.o: %.cpp $(CXX) $(CXXFLAGS) -c $*.cpp everything: tmt example test_exc nl_ex sl_ex garch newmat_lobj = newmat1.o newmat2.o newmat3.o newmat4.o newmat5.o newmat6.o newmat7.o newmat8.o newmatex.o bandmat.o submat.o myexcept.o cholesky.o evalue.o fft.o hholder.o jacobi.o newfft.o sort.o svd.o newmatrm.o newmat9.o libnewmat.a: $(newmat_lobj) $(AR) -cr $@ $(newmat_lobj) ranlib $@ tmt_obj = tmt.o tmt1.o tmt2.o tmt3.o tmt4.o tmt5.o tmt6.o tmt7.o tmt8.o tmt9.o tmta.o tmtb.o tmtc.o tmtd.o tmte.o tmtf.o tmtg.o tmth.o tmti.o tmtj.o tmtk.o tmtl.o tmtm.o tmt: $(tmt_obj) libnewmat.a $(CXX) -o $@ $(tmt_obj) -L. -lnewmat -lm example_obj = example.o example: $(example_obj) libnewmat.a $(CXX) -o $@ $(example_obj) -L. -lnewmat -lm test_exc_obj = test_exc.o test_exc: $(test_exc_obj) libnewmat.a $(CXX) -o $@ $(test_exc_obj) -L. -lnewmat -lm nl_ex_obj = nl_ex.o newmatnl.o nl_ex: $(nl_ex_obj) libnewmat.a $(CXX) -o $@ $(nl_ex_obj) -L. -lnewmat -lm sl_ex_obj = sl_ex.o solution.o myexcept.o sl_ex: $(sl_ex_obj) $(CXX) -o $@ $(sl_ex_obj) -L. -lm garch_obj = garch.o newmatnl.o garch: $(garch_obj) libnewmat.a $(CXX) -o $@ $(garch_obj) -L. -lnewmat -lm newmat1.o: newmat1.cpp newmat.h include.h boolean.h myexcept.h newmat2.o: newmat2.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat3.o: newmat3.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat4.o: newmat4.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat5.o: newmat5.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat6.o: newmat6.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat7.o: newmat7.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat8.o: newmat8.cpp include.h newmat.h newmatrc.h precisio.h boolean.h myexcept.h controlw.h newmatex.o: newmatex.cpp include.h newmat.h boolean.h myexcept.h bandmat.o: bandmat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h submat.o: submat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h myexcept.o: myexcept.cpp include.h myexcept.h cholesky.o: cholesky.cpp include.h newmat.h boolean.h myexcept.h evalue.o: evalue.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h fft.o: fft.cpp include.h newmatap.h newmat.h boolean.h myexcept.h hholder.o: hholder.cpp include.h newmatap.h newmat.h boolean.h myexcept.h jacobi.o: jacobi.cpp include.h newmatap.h precisio.h newmatrm.h newmat.h boolean.h myexcept.h newfft.o: newfft.cpp newmatap.h newmat.h include.h boolean.h myexcept.h sort.o: sort.cpp include.h newmatap.h newmat.h boolean.h myexcept.h svd.o: svd.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h newmatrm.o: newmatrm.cpp newmat.h newmatrm.h include.h boolean.h myexcept.h newmat9.o: newmat9.cpp include.h newmat.h newmatio.h newmatrc.h boolean.h myexcept.h controlw.h tmt.o: tmt.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt1.o: tmt1.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt2.o: tmt2.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt3.o: tmt3.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt4.o: tmt4.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt5.o: tmt5.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt6.o: tmt6.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt7.o: tmt7.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt8.o: tmt8.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt9.o: tmt9.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmta.o: tmta.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtb.o: tmtb.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtc.o: tmtc.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtd.o: tmtd.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmte.o: tmte.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtf.o: tmtf.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtg.o: tmtg.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmth.o: tmth.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmti.o: tmti.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtj.o: tmtj.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtk.o: tmtk.cpp include.h newmatap.h newmatio.h tmt.h newmat.h boolean.h myexcept.h tmtl.o: tmtl.cpp newmat.h tmt.h include.h boolean.h myexcept.h tmtm.o: tmtm.cpp newmat.h tmt.h include.h boolean.h myexcept.h example.o: example.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h test_exc.o: test_exc.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h nl_ex.o: nl_ex.cpp newmatnl.h newmatio.h newmat.h include.h boolean.h myexcept.h newmatnl.o: newmatnl.cpp newmatap.h newmatnl.h newmat.h include.h boolean.h myexcept.h sl_ex.o: sl_ex.cpp include.h solution.h boolean.h myexcept.h solution.o: solution.cpp include.h boolean.h myexcept.h solution.h garch.o: garch.cpp newmatap.h newmatio.h newmatnl.h newmat.h include.h boolean.h myexcept.h tmt.txx: tmt $(PRE)tmt > tmt.txx $(DIFF) tmt.txt tmt.txx example.txx: example $(PRE)example > example.txx $(DIFF) example.txt example.txx test_exc.txx: test_exc $(PRE)test_exc > test_exc.txx $(DIFF) test_exc.txt test_exc.txx nl_ex.txx: nl_ex $(PRE)nl_ex > nl_ex.txx $(DIFF) nl_ex.txt nl_ex.txx sl_ex.txx: sl_ex $(PRE)sl_ex > sl_ex.txx $(DIFF) sl_ex.txt sl_ex.txx garch.txx: garch $(PRE)garch > garch.txx $(DIFF) garch.txt garch.txx newmat-1.10.4/nm_m6.mak0000644001161000116100000001414410407125167013011 0ustar rzrrzr conlibs = libc.lib kernel32.lib DIFF = sdiff PRE = .SUFFIXES: .cpp .cpp.obj: cl -c -W3 -Ox -GX $*.cpp everything: tmt.exe example.exe test_exc.exe nl_ex.exe sl_ex.exe garch.exe newmat_lobj = newmat1.obj newmat2.obj newmat3.obj newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj newmatex.obj bandmat.obj submat.obj myexcept.obj cholesky.obj evalue.obj fft.obj hholder.obj jacobi.obj newfft.obj sort.obj svd.obj newmatrm.obj newmat9.obj newmat.lib: $(newmat_lobj) lib -Out:$@ $(newmat_lobj) tmt_obj = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmtm.obj tmt.exe: $(tmt_obj) newmat.lib link -Out:$@ $(conlibs) $(tmt_obj) newmat.lib example_obj = example.obj example.exe: $(example_obj) newmat.lib link -Out:$@ $(conlibs) $(example_obj) newmat.lib test_exc_obj = test_exc.obj test_exc.exe: $(test_exc_obj) newmat.lib link -Out:$@ $(conlibs) $(test_exc_obj) newmat.lib nl_ex_obj = nl_ex.obj newmatnl.obj nl_ex.exe: $(nl_ex_obj) newmat.lib link -Out:$@ $(conlibs) $(nl_ex_obj) newmat.lib sl_ex_obj = sl_ex.obj solution.obj myexcept.obj sl_ex.exe: $(sl_ex_obj) link -Out:$@ $(conlibs) $(sl_ex_obj) garch_obj = garch.obj newmatnl.obj garch.exe: $(garch_obj) newmat.lib link -Out:$@ $(conlibs) $(garch_obj) newmat.lib newmat1.obj: newmat1.cpp newmat.h include.h boolean.h myexcept.h newmat2.obj: newmat2.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat3.obj: newmat3.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat4.obj: newmat4.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat5.obj: newmat5.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat6.obj: newmat6.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat7.obj: newmat7.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat8.obj: newmat8.cpp include.h newmat.h newmatrc.h precisio.h boolean.h myexcept.h controlw.h newmatex.obj: newmatex.cpp include.h newmat.h boolean.h myexcept.h bandmat.obj: bandmat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h submat.obj: submat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h myexcept.obj: myexcept.cpp include.h myexcept.h cholesky.obj: cholesky.cpp include.h newmat.h boolean.h myexcept.h evalue.obj: evalue.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h fft.obj: fft.cpp include.h newmatap.h newmat.h boolean.h myexcept.h hholder.obj: hholder.cpp include.h newmatap.h newmat.h boolean.h myexcept.h jacobi.obj: jacobi.cpp include.h newmatap.h precisio.h newmatrm.h newmat.h boolean.h myexcept.h newfft.obj: newfft.cpp newmatap.h newmat.h include.h boolean.h myexcept.h sort.obj: sort.cpp include.h newmatap.h newmat.h boolean.h myexcept.h svd.obj: svd.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h newmatrm.obj: newmatrm.cpp newmat.h newmatrm.h include.h boolean.h myexcept.h newmat9.obj: newmat9.cpp include.h newmat.h newmatio.h newmatrc.h boolean.h myexcept.h controlw.h tmt.obj: tmt.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt1.obj: tmt1.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt2.obj: tmt2.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt3.obj: tmt3.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt4.obj: tmt4.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt5.obj: tmt5.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt6.obj: tmt6.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt7.obj: tmt7.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt8.obj: tmt8.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt9.obj: tmt9.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmta.obj: tmta.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtb.obj: tmtb.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtc.obj: tmtc.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtd.obj: tmtd.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmte.obj: tmte.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtf.obj: tmtf.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtg.obj: tmtg.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmth.obj: tmth.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmti.obj: tmti.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtj.obj: tmtj.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtk.obj: tmtk.cpp include.h newmatap.h newmatio.h tmt.h newmat.h boolean.h myexcept.h tmtl.obj: tmtl.cpp newmat.h tmt.h include.h boolean.h myexcept.h tmtm.obj: tmtm.cpp newmat.h tmt.h include.h boolean.h myexcept.h example.obj: example.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h test_exc.obj: test_exc.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h nl_ex.obj: nl_ex.cpp newmatnl.h newmatio.h newmat.h include.h boolean.h myexcept.h newmatnl.obj: newmatnl.cpp newmatap.h newmatnl.h newmat.h include.h boolean.h myexcept.h sl_ex.obj: sl_ex.cpp include.h solution.h boolean.h myexcept.h solution.obj: solution.cpp include.h boolean.h myexcept.h solution.h garch.obj: garch.cpp newmatap.h newmatio.h newmatnl.h newmat.h include.h boolean.h myexcept.h tmt.txx: tmt.exe $(PRE)tmt > tmt.txx $(DIFF) tmt.txt tmt.txx example.txx: example.exe $(PRE)example > example.txx $(DIFF) example.txt example.txx test_exc.txx: test_exc.exe $(PRE)test_exc > test_exc.txx $(DIFF) test_exc.txt test_exc.txx nl_ex.txx: nl_ex.exe $(PRE)nl_ex > nl_ex.txx $(DIFF) nl_ex.txt nl_ex.txx sl_ex.txx: sl_ex.exe $(PRE)sl_ex > sl_ex.txx $(DIFF) sl_ex.txt sl_ex.txx garch.txx: garch.exe $(PRE)garch > garch.txx $(DIFF) garch.txt garch.txx newmat-1.10.4/nm_m8.mak0000644001161000116100000001413510407125173013010 0ustar rzrrzr conlibs = kernel32.lib DIFF = sdiff PRE = .SUFFIXES: .cpp .cpp.obj: cl -c -W3 -Ox -EHsc $*.cpp everything: tmt.exe example.exe test_exc.exe nl_ex.exe sl_ex.exe garch.exe newmat_lobj = newmat1.obj newmat2.obj newmat3.obj newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj newmatex.obj bandmat.obj submat.obj myexcept.obj cholesky.obj evalue.obj fft.obj hholder.obj jacobi.obj newfft.obj sort.obj svd.obj newmatrm.obj newmat9.obj newmat.lib: $(newmat_lobj) lib -Out:$@ $(newmat_lobj) tmt_obj = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmtm.obj tmt.exe: $(tmt_obj) newmat.lib link -Out:$@ $(conlibs) $(tmt_obj) newmat.lib example_obj = example.obj example.exe: $(example_obj) newmat.lib link -Out:$@ $(conlibs) $(example_obj) newmat.lib test_exc_obj = test_exc.obj test_exc.exe: $(test_exc_obj) newmat.lib link -Out:$@ $(conlibs) $(test_exc_obj) newmat.lib nl_ex_obj = nl_ex.obj newmatnl.obj nl_ex.exe: $(nl_ex_obj) newmat.lib link -Out:$@ $(conlibs) $(nl_ex_obj) newmat.lib sl_ex_obj = sl_ex.obj solution.obj myexcept.obj sl_ex.exe: $(sl_ex_obj) link -Out:$@ $(conlibs) $(sl_ex_obj) garch_obj = garch.obj newmatnl.obj garch.exe: $(garch_obj) newmat.lib link -Out:$@ $(conlibs) $(garch_obj) newmat.lib newmat1.obj: newmat1.cpp newmat.h include.h boolean.h myexcept.h newmat2.obj: newmat2.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat3.obj: newmat3.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat4.obj: newmat4.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat5.obj: newmat5.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat6.obj: newmat6.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat7.obj: newmat7.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat8.obj: newmat8.cpp include.h newmat.h newmatrc.h precisio.h boolean.h myexcept.h controlw.h newmatex.obj: newmatex.cpp include.h newmat.h boolean.h myexcept.h bandmat.obj: bandmat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h submat.obj: submat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h myexcept.obj: myexcept.cpp include.h myexcept.h cholesky.obj: cholesky.cpp include.h newmat.h boolean.h myexcept.h evalue.obj: evalue.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h fft.obj: fft.cpp include.h newmatap.h newmat.h boolean.h myexcept.h hholder.obj: hholder.cpp include.h newmatap.h newmat.h boolean.h myexcept.h jacobi.obj: jacobi.cpp include.h newmatap.h precisio.h newmatrm.h newmat.h boolean.h myexcept.h newfft.obj: newfft.cpp newmatap.h newmat.h include.h boolean.h myexcept.h sort.obj: sort.cpp include.h newmatap.h newmat.h boolean.h myexcept.h svd.obj: svd.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h newmatrm.obj: newmatrm.cpp newmat.h newmatrm.h include.h boolean.h myexcept.h newmat9.obj: newmat9.cpp include.h newmat.h newmatio.h newmatrc.h boolean.h myexcept.h controlw.h tmt.obj: tmt.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt1.obj: tmt1.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt2.obj: tmt2.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt3.obj: tmt3.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt4.obj: tmt4.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt5.obj: tmt5.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt6.obj: tmt6.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt7.obj: tmt7.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt8.obj: tmt8.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt9.obj: tmt9.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmta.obj: tmta.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtb.obj: tmtb.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtc.obj: tmtc.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtd.obj: tmtd.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmte.obj: tmte.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtf.obj: tmtf.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtg.obj: tmtg.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmth.obj: tmth.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmti.obj: tmti.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtj.obj: tmtj.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtk.obj: tmtk.cpp include.h newmatap.h newmatio.h tmt.h newmat.h boolean.h myexcept.h tmtl.obj: tmtl.cpp newmat.h tmt.h include.h boolean.h myexcept.h tmtm.obj: tmtm.cpp newmat.h tmt.h include.h boolean.h myexcept.h example.obj: example.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h test_exc.obj: test_exc.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h nl_ex.obj: nl_ex.cpp newmatnl.h newmatio.h newmat.h include.h boolean.h myexcept.h newmatnl.obj: newmatnl.cpp newmatap.h newmatnl.h newmat.h include.h boolean.h myexcept.h sl_ex.obj: sl_ex.cpp include.h solution.h boolean.h myexcept.h solution.obj: solution.cpp include.h boolean.h myexcept.h solution.h garch.obj: garch.cpp newmatap.h newmatio.h newmatnl.h newmat.h include.h boolean.h myexcept.h tmt.txx: tmt.exe $(PRE)tmt > tmt.txx $(DIFF) tmt.txt tmt.txx example.txx: example.exe $(PRE)example > example.txx $(DIFF) example.txt example.txx test_exc.txx: test_exc.exe $(PRE)test_exc > test_exc.txx $(DIFF) test_exc.txt test_exc.txx nl_ex.txx: nl_ex.exe $(PRE)nl_ex > nl_ex.txx $(DIFF) nl_ex.txt nl_ex.txx sl_ex.txx: sl_ex.exe $(PRE)sl_ex > sl_ex.txx $(DIFF) sl_ex.txt sl_ex.txx garch.txx: garch.exe $(PRE)garch > garch.txx $(DIFF) garch.txt garch.txx newmat-1.10.4/nm_ow.mak0000644001161000116100000001442610407125176013117 0ustar rzrrzr.cpp.obj: wcl386 -c -xs $*.cpp DIFF = sdiff PRE = everything: tmt.exe example.exe test_exc.exe nl_ex.exe sl_ex.exe garch.exe newmat_lobj = newmat1.obj newmat2.obj newmat3.obj newmat4.obj newmat5.obj newmat6.obj newmat7.obj newmat8.obj newmatex.obj bandmat.obj submat.obj myexcept.obj cholesky.obj evalue.obj fft.obj hholder.obj jacobi.obj newfft.obj sort.obj svd.obj newmatrm.obj newmat9.obj newmat_pobj = +newmat1.obj +newmat2.obj +newmat3.obj +newmat4.obj +newmat5.obj +newmat6.obj +newmat7.obj +newmat8.obj +newmatex.obj +bandmat.obj +submat.obj +myexcept.obj +cholesky.obj +evalue.obj +fft.obj +hholder.obj +jacobi.obj +newfft.obj +sort.obj +svd.obj +newmatrm.obj +newmat9.obj newmat.lib: $(newmat_lobj) wlib -n $@ $(newmat_pobj) tmt_obj = tmt.obj tmt1.obj tmt2.obj tmt3.obj tmt4.obj tmt5.obj tmt6.obj tmt7.obj tmt8.obj tmt9.obj tmta.obj tmtb.obj tmtc.obj tmtd.obj tmte.obj tmtf.obj tmtg.obj tmth.obj tmti.obj tmtj.obj tmtk.obj tmtl.obj tmtm.obj tmt.exe: $(tmt_obj) newmat.lib wcl386 -fe=$@ $(tmt_obj) newmat.lib example_obj = example.obj example.exe: $(example_obj) newmat.lib wcl386 -fe=$@ $(example_obj) newmat.lib test_exc_obj = test_exc.obj test_exc.exe: $(test_exc_obj) newmat.lib wcl386 -fe=$@ $(test_exc_obj) newmat.lib nl_ex_obj = nl_ex.obj newmatnl.obj nl_ex.exe: $(nl_ex_obj) newmat.lib wcl386 -fe=$@ $(nl_ex_obj) newmat.lib sl_ex_obj = sl_ex.obj solution.obj myexcept.obj sl_ex.exe: $(sl_ex_obj) wcl386 -fe=$@ $(sl_ex_obj) garch_obj = garch.obj newmatnl.obj garch.exe: $(garch_obj) newmat.lib wcl386 -fe=$@ $(garch_obj) newmat.lib newmat1.obj: newmat1.cpp newmat.h include.h boolean.h myexcept.h newmat2.obj: newmat2.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat3.obj: newmat3.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat4.obj: newmat4.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat5.obj: newmat5.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat6.obj: newmat6.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat7.obj: newmat7.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h newmat8.obj: newmat8.cpp include.h newmat.h newmatrc.h precisio.h boolean.h myexcept.h controlw.h newmatex.obj: newmatex.cpp include.h newmat.h boolean.h myexcept.h bandmat.obj: bandmat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h submat.obj: submat.cpp include.h newmat.h newmatrc.h boolean.h myexcept.h controlw.h myexcept.obj: myexcept.cpp include.h myexcept.h cholesky.obj: cholesky.cpp include.h newmat.h boolean.h myexcept.h evalue.obj: evalue.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h fft.obj: fft.cpp include.h newmatap.h newmat.h boolean.h myexcept.h hholder.obj: hholder.cpp include.h newmatap.h newmat.h boolean.h myexcept.h jacobi.obj: jacobi.cpp include.h newmatap.h precisio.h newmatrm.h newmat.h boolean.h myexcept.h newfft.obj: newfft.cpp newmatap.h newmat.h include.h boolean.h myexcept.h sort.obj: sort.cpp include.h newmatap.h newmat.h boolean.h myexcept.h svd.obj: svd.cpp include.h newmatap.h newmatrm.h precisio.h newmat.h boolean.h myexcept.h newmatrm.obj: newmatrm.cpp newmat.h newmatrm.h include.h boolean.h myexcept.h newmat9.obj: newmat9.cpp include.h newmat.h newmatio.h newmatrc.h boolean.h myexcept.h controlw.h tmt.obj: tmt.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt1.obj: tmt1.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt2.obj: tmt2.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt3.obj: tmt3.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt4.obj: tmt4.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt5.obj: tmt5.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt6.obj: tmt6.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt7.obj: tmt7.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmt8.obj: tmt8.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmt9.obj: tmt9.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmta.obj: tmta.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtb.obj: tmtb.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtc.obj: tmtc.cpp include.h newmat.h tmt.h boolean.h myexcept.h tmtd.obj: tmtd.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmte.obj: tmte.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtf.obj: tmtf.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtg.obj: tmtg.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmth.obj: tmth.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmti.obj: tmti.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtj.obj: tmtj.cpp include.h newmatap.h tmt.h newmat.h boolean.h myexcept.h tmtk.obj: tmtk.cpp include.h newmatap.h newmatio.h tmt.h newmat.h boolean.h myexcept.h tmtl.obj: tmtl.cpp newmat.h tmt.h include.h boolean.h myexcept.h tmtm.obj: tmtm.cpp newmat.h tmt.h include.h boolean.h myexcept.h example.obj: example.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h test_exc.obj: test_exc.cpp newmatap.h newmatio.h newmat.h include.h boolean.h myexcept.h nl_ex.obj: nl_ex.cpp newmatnl.h newmatio.h newmat.h include.h boolean.h myexcept.h newmatnl.obj: newmatnl.cpp newmatap.h newmatnl.h newmat.h include.h boolean.h myexcept.h sl_ex.obj: sl_ex.cpp include.h solution.h boolean.h myexcept.h solution.obj: solution.cpp include.h boolean.h myexcept.h solution.h garch.obj: garch.cpp newmatap.h newmatio.h newmatnl.h newmat.h include.h boolean.h myexcept.h tmt.txx: tmt.exe $(PRE)tmt > tmt.txx $(DIFF) tmt.txt tmt.txx example.txx: example.exe $(PRE)example > example.txx $(DIFF) example.txt example.txx test_exc.txx: test_exc.exe $(PRE)test_exc > test_exc.txx $(DIFF) test_exc.txt test_exc.txx nl_ex.txx: nl_ex.exe $(PRE)nl_ex > nl_ex.txx $(DIFF) nl_ex.txt nl_ex.txx sl_ex.txx: sl_ex.exe $(PRE)sl_ex > sl_ex.txx $(DIFF) sl_ex.txt sl_ex.txx garch.txx: garch.exe $(PRE)garch > garch.txx $(DIFF) garch.txt garch.txx newmat-1.10.4/nm_targ.txt0000644001161000116100000000006207330252770013467 0ustar rzrrzrnewmat.lfl tmt example test_exc nl_ex sl_ex garch newmat-1.10.4/precisio.h0000644001161000116100000001473510322324761013274 0ustar rzrrzr/// \ingroup newmat ///@{ /// \file precisio.h /// Floating point precision constants. #ifndef PRECISION_LIB #define PRECISION_LIB 0 #define WANT_MATH #include "include.h" // in case being used as stand alone #ifdef _STANDARD_ // standard library available #include #endif #ifdef use_namespace namespace NEWMAT { #endif #ifdef _STANDARD_ // standard library available #ifdef OPT_COMPATIBLE #include // for FLT_MAX #endif using namespace std; /// Floating point precision. class FloatingPointPrecision { public: static int Dig() // number of decimal digits or precision { return numeric_limits::digits10 ; } static Real Epsilon() // smallest number such that 1+Eps!=Eps { return numeric_limits::epsilon(); } static int Mantissa() // bits in mantisa { return numeric_limits::digits; } static Real Maximum() // maximum value { return numeric_limits::max(); } static int MaximumDecimalExponent() // maximum decimal exponent { return numeric_limits::max_exponent10; } static int MaximumExponent() // maximum binary exponent { return numeric_limits::max_exponent; } static Real LnMaximum() // natural log of maximum { return (Real)log(Maximum()); } static Real Minimum() // minimum positive value { return numeric_limits::min(); } static int MinimumDecimalExponent() // minimum decimal exponent { return numeric_limits::min_exponent10; } static int MinimumExponent() // minimum binary exponent { return numeric_limits::min_exponent; } static Real LnMinimum() // natural log of minimum { return (Real)log(Minimum()); } static int Radix() // exponent radix { return numeric_limits::radix; } static int Rounds() // addition rounding (1 = does round) { return numeric_limits::round_style == round_to_nearest ? 1 : 0; } }; #else // _STANDARD_ not defined #ifndef SystemV // if there is float.h #ifdef USING_FLOAT /// Floating point precision (type float). class FloatingPointPrecision { public: static int Dig() { return FLT_DIG; } // number of decimal digits or precision static Real Epsilon() { return FLT_EPSILON; } // smallest number such that 1+Eps!=Eps static int Mantissa() { return FLT_MANT_DIG; } // bits in mantisa static Real Maximum() { return FLT_MAX; } // maximum value static int MaximumDecimalExponent() { return FLT_MAX_10_EXP; } // maximum decimal exponent static int MaximumExponent() { return FLT_MAX_EXP; } // maximum binary exponent static Real LnMaximum() { return (Real)log(Maximum()); } // natural log of maximum static Real Minimum() { return FLT_MIN; } // minimum positive value static int MinimumDecimalExponent() { return FLT_MIN_10_EXP; } // minimum decimal exponent static int MinimumExponent() { return FLT_MIN_EXP; } // minimum binary exponent static Real LnMinimum() { return (Real)log(Minimum()); } // natural log of minimum static int Radix() { return FLT_RADIX; } // exponent radix static int Rounds() { return FLT_ROUNDS; } // addition rounding (1 = does round) }; #endif // USING_FLOAT #ifdef USING_DOUBLE /// Floating point precision (type double). class FloatingPointPrecision { public: static int Dig() { return DBL_DIG; } // number of decimal digits or precision static Real Epsilon() { return DBL_EPSILON; } // smallest number such that 1+Eps!=Eps static int Mantissa() { return DBL_MANT_DIG; } // bits in mantisa static Real Maximum() { return DBL_MAX; } // maximum value static int MaximumDecimalExponent() { return DBL_MAX_10_EXP; } // maximum decimal exponent static int MaximumExponent() { return DBL_MAX_EXP; } // maximum binary exponent static Real LnMaximum() { return (Real)log(Maximum()); } // natural log of maximum static Real Minimum() { //#ifdef __BCPLUSPLUS__ // return 2.225074e-308; // minimum positive value //#else return DBL_MIN; //#endif } static int MinimumDecimalExponent() { return DBL_MIN_10_EXP; } // minimum decimal exponent static int MinimumExponent() { return DBL_MIN_EXP; } // minimum binary exponent static Real LnMinimum() { return (Real)log(Minimum()); } // natural log of minimum static int Radix() { return FLT_RADIX; } // exponent radix static int Rounds() { return FLT_ROUNDS; } // addition rounding (1 = does round) }; #endif // USING_DOUBLE #else // if there is no float.h #ifdef OPT_COMPATIBLE #define FLT_MAX MAXFLOAT #endif #ifdef USING_FLOAT /// Floating point precision (type float). class FloatingPointPrecision { public: static Real Epsilon() { return pow(2.0,(int)(1-FSIGNIF)); } // smallest number such that 1+Eps!=Eps static Real Maximum() { return MAXFLOAT; } // maximum value static Real LnMaximum() { return (Real)log(Maximum()); } // natural log of maximum static Real Minimum() { return MINFLOAT; } // minimum positive value static Real LnMinimum() { return (Real)log(Minimum()); } // natural log of minimum }; #endif // USING_FLOAT #ifdef USING_DOUBLE /// Floating point precision (type double). class FloatingPointPrecision { public: static Real Epsilon() { return pow(2.0,(int)(1-DSIGNIF)); } // smallest number such that 1+Eps!=Eps static Real Maximum() { return MAXDOUBLE; } // maximum value static Real LnMaximum() { return LN_MAXDOUBLE; } // natural log of maximum static Real Minimum() { return MINDOUBLE; } static Real LnMinimum() { return LN_MINDOUBLE; } // natural log of minimum }; #endif // USING_DOUBLE #endif // SystemV #endif // _STANDARD_ #ifdef use_namespace } #endif // use_namespace #endif // PRECISION_LIB ///@} newmat-1.10.4/rbd.css0000644001161000116100000000256510210751335012562 0ustar rzrrzr/* Style sheet - if you are saving my html files, please also save this file as rbd.css */ h1 { font-family: Arial, Helvetica, sans-serif; font-size: 20pt; color: maroon } h2 { font-family: Arial, Helvetica, sans-serif; font-size: 16pt; color: maroon } h3 { font-family: Arial, Helvetica, sans-serif; font-size: 14pt; color: maroon } h4 { font-family: Arial, Helvetica, sans-serif; font-size: 12pt; color: maroon } body { font-family: "Times New Roman", Times, serif; background-color: white } body.gray { font-family: "Times New Roman", Times, serif; background-color: #CCCCCC } p { font-family: "Times New Roman", Times, serif; margin-top: 8; margin-bottom: 8 } p.small { font-family: "Times New Roman", Times, serif; font-size: 10pt; margin-top: 8; margin-bottom: 8 } ul { line-height: 100%; margin-top: 2; margin-bottom: 2 } li { margin-top: 2; margin-bottom: 2; font-size: 10pt } tt { font-family: "Courier New", Courier, monospaced; font-size: 10pt } pre { font-family: "Courier New", Courier, monospaced; font-size: 10pt } pre.small { font-family: "Courier New", Courier, monospaced; font-size: 8pt } hr { color: maroon } a:link { color: blue } a:visited { color: green } a:active { color: red } table { font-size: 10pt } .question { color: navy; }newmat-1.10.4/sl_ex.cpp0000644001161000116100000000121407330263640013113 0ustar rzrrzr// This is an example of the use of solution to find the cube root of // the integers -10 to 10 // you will need to compile and link solution.cpp and except.cpp #define WANT_STREAM #define WANT_MATH #include "include.h" #include "solution.h" #ifdef use_namespace using namespace RBD_LIBRARIES; #endif // the cube class class Cube : public R1_R1 { Real operator()() { return x*x*x; } }; int main() { // construct the Cube object Cube cube; // and then the solve object OneDimSolve cube_root(cube); // Now do the solves for (int i=-10; i<=10; i++) cout << i << " " << cube_root.Solve(i,0,1.5) << endl; return 0; } newmat-1.10.4/sl_ex.txt0000644001161000116100000000037707215546666013177 0ustar rzrrzr-10 -2.15443 -9 -2.08008 -8 -2 -7 -1.91293 -6 -1.81712 -5 -1.70998 -4 -1.5874 -3 -1.44225 -2 -1.25992 -1 -1.00001 0 0 1 1.00001 2 1.25992 3 1.44225 4 1.58741 5 1.70998 6 1.81712 7 1.91293 8 2 9 2.08008 10 2.15443 newmat-1.10.4/solution.cpp0000644001161000116100000001362610406436337013672 0ustar rzrrzr//$$ solution.cpp // solve routines // Copyright (C) 1994: R B Davies #define WANT_STREAM // include.h will get stream fns #define WANT_MATH // include.h will get math fns #include "include.h" #include "boolean.h" #include "myexcept.h" #include "solution.h" #ifdef use_namespace namespace RBD_COMMON { #endif void R1_R1::Set(Real X) { if ((!minXinf && X <= minX) || (!maxXinf && X >= maxX)) Throw(SolutionException("X value out of range")); x = X; xSet = true; } R1_R1::operator Real() { if (!xSet) Throw(SolutionException("Value of X not set")); Real y = operator()(); return y; } unsigned long SolutionException::Select; SolutionException::SolutionException(const char* a_what) : BaseException() { Select = BaseException::Select; AddMessage("Error detected by solution package\n"); AddMessage(a_what); AddMessage("\n"); if (a_what) Tracer::AddTrace(); }; inline Real square(Real x) { return x*x; } void OneDimSolve::LookAt(int V) { lim--; if (!lim) Throw(SolutionException("Does not converge")); Last = V; Real yy = function(x[V]) - YY; Finish = (fabs(yy) <= accY) || (Captured && fabs(x[L]-x[U]) <= accX ); y[V] = vpol*yy; } void OneDimSolve::HFlip() { hpol=-hpol; State(U,C,L); } void OneDimSolve::VFlip() { vpol = -vpol; y[0] = -y[0]; y[1] = -y[1]; y[2] = -y[2]; } void OneDimSolve::Flip() { hpol=-hpol; vpol=-vpol; State(U,C,L); y[0] = -y[0]; y[1] = -y[1]; y[2] = -y[2]; } void OneDimSolve::State(int I, int J, int K) { L=I; C=J; U=K; } void OneDimSolve::Linear(int I, int J, int K) { x[J] = (x[I]*y[K] - x[K]*y[I])/(y[K] - y[I]); // cout << "Linear\n"; } void OneDimSolve::Quadratic(int I, int J, int K) { // result to overwrite I Real YJK, YIK, YIJ, XKI, XKJ; YJK = y[J] - y[K]; YIK = y[I] - y[K]; YIJ = y[I] - y[J]; XKI = (x[K] - x[I]); XKJ = (x[K]*y[J] - x[J]*y[K])/YJK; if ( square(YJK/YIK)>(x[K] - x[J])/XKI || square(YIJ/YIK)>(x[J] - x[I])/XKI ) { x[I] = XKJ; // cout << "Quadratic - exceptional\n"; } else { XKI = (x[K]*y[I] - x[I]*y[K])/YIK; x[I] = (XKJ*y[I] - XKI*y[J])/YIJ; // cout << "Quadratic - normal\n"; } } Real OneDimSolve::Solve(Real Y, Real X, Real Dev, int Lim) { enum Loop { start, captured1, captured2, binary, finish }; Tracer et("OneDimSolve::Solve"); lim=Lim; Captured = false; if (Dev==0.0) Throw(SolutionException("Dev is zero")); L=0; C=1; U=2; vpol=1; hpol=1; y[C]=0.0; y[U]=0.0; if (Dev<0.0) { hpol=-1; Dev = -Dev; } YY=Y; // target value x[L] = X; // initial trial value if (!function.IsValid(X)) Throw(SolutionException("Starting value is invalid")); Loop TheLoop = start; for (;;) { switch (TheLoop) { case start: LookAt(L); if (Finish) { TheLoop = finish; break; } if (y[L]>0.0) VFlip(); // so Y[L] < 0 x[U] = X + Dev * hpol; if (!function.maxXinf && x[U] > function.maxX) x[U] = (function.maxX + X) / 2.0; if (!function.minXinf && x[U] < function.minX) x[U] = (function.minX + X) / 2.0; LookAt(U); if (Finish) { TheLoop = finish; break; } if (y[U] > 0.0) { TheLoop = captured1; Captured = true; break; } if (y[U] == y[L]) Throw(SolutionException("Function is flat")); if (y[U] < y[L]) HFlip(); // Change direction State(L,U,C); for (i=0; i<20; i++) { // cout << "Searching for crossing point\n"; // Have L C then crossing point, Y[L] function.maxX) x[U] = (function.maxX + x[C]) / 2.0; if (!function.minXinf && x[U] < function.minX) x[U] = (function.minX + x[C]) / 2.0; LookAt(U); if (Finish) { TheLoop = finish; break; } if (y[U] > 0) { TheLoop = captured2; Captured = true; break; } if (y[U] < y[C]) Throw(SolutionException("Function is not monotone")); Dev *= 2.0; State(C,U,L); } if (TheLoop != start ) break; Throw(SolutionException("Cannot locate a crossing point")); case captured1: // cout << "Captured - 1\n"; // We have 2 points L and U with crossing between them Linear(L,C,U); // linear interpolation // - result to C LookAt(C); if (Finish) { TheLoop = finish; break; } if (y[C] > 0.0) Flip(); // Want y[C] < 0 if (y[C] < 0.5*y[L]) { State(C,L,U); TheLoop = binary; break; } case captured2: // cout << "Captured - 2\n"; // We have L,C before crossing, U after crossing Quadratic(L,C,U); // quad interpolation // - result to L State(C,L,U); if ((x[C] - x[L])*hpol <= 0.0 || (x[C] - x[U])*hpol >= 0.0) { TheLoop = captured1; break; } LookAt(C); if (Finish) { TheLoop = finish; break; } // cout << "Through first stage\n"; if (y[C] > 0.0) Flip(); if (y[C] > 0.5*y[L]) { TheLoop = captured2; break; } else { State(C,L,U); TheLoop = captured1; break; } case binary: // We have L, U around crossing - do binary search // cout << "Binary\n"; for (i=3; i; i--) { x[C] = 0.5*(x[L]+x[U]); LookAt(C); if (Finish) { TheLoop = finish; break; } if (y[C]>0.0) State(L,U,C); else State(C,L,U); } if (TheLoop != binary) break; TheLoop = captured1; break; case finish: return x[Last]; } } } bool R1_R1::IsValid(Real X) { Set(X); return (minXinf || x > minX) && (maxXinf || x < maxX); } #ifdef use_namespace } #endif newmat-1.10.4/solution.h0000644001161000116100000000622510406434354013331 0ustar rzrrzr//$$ solution.h // solve routines #include "boolean.h" #include "myexcept.h" #ifdef use_namespace namespace RBD_COMMON { #endif // Solve the equation f(x)=y for x where f is a monotone continuous // function of x // Essentially Brent s method // You need to derive a class from R1_R1 and override "operator()" // with the function you want to solve. // Use an object from this class in OneDimSolve class R1_R1 { // the prototype for a Real function of a Real variable // you need to derive your function from this one and put in your // function for operator() at least. You probably also want to set up a // constructor to put in additional parameter values (e.g. that will not // vary during a solve) protected: Real x; // Current x value bool xSet; // true if a value assigned to x public: Real minX, maxX; // range of value x bool minXinf, maxXinf; // true if these are infinite R1_R1() : xSet(false), minXinf(true), maxXinf(true) {} virtual Real operator()() = 0; // function value at current x // set current x virtual void Set(Real X); // set x, check OK Real operator()(Real X) { Set(X); return operator()(); } // set x, return value virtual bool IsValid(Real X); operator Real(); // implicit conversion virtual ~R1_R1() {} // to keep gnu happy }; class SolutionException : public BaseException { public: static unsigned long Select; SolutionException(const char* a_what = 0); }; class OneDimSolve { R1_R1& function; // reference to the function Real accX; // accuracy in X direction Real accY; // accuracy in Y direction int lim; // maximum number of iterations public: OneDimSolve(R1_R1& f, Real AccY = 0.0001, Real AccX = 0.0) : function(f), accX(AccX), accY(AccY) {} // f is an R1_R1 function Real Solve(Real Y, Real X, Real Dev, int Lim=100); // Solve for x in Y=f(x) // X is the initial trial value of x // X+Dev is the second trial value // program returns a value of x such that // |Y-f(x)| <= accY or |f.inv(Y)-x| <= accX private: Real x[3], y[3]; // Trial values of X and Y int L,C,U,Last; // Locations of trial values int vpol, hpol; // polarities Real YY; // target value int i; void LookAt(int); // get new value of function bool Finish; // true if LookAt finds conv. bool Captured; // true when target surrounded void VFlip(); void HFlip(); void Flip(); void State(int I, int J, int K); void Linear(int, int, int); void Quadratic(int, int, int); }; #ifdef use_namespace } #endif // body file: solution.cpp newmat-1.10.4/sort.cpp0000644001161000116100000001654107414432762013007 0ustar rzrrzr//$$ sort.cpp Sorting // Copyright (C) 1991,2,3,4: R B Davies #define WANT_MATH #include "include.h" #include "newmatap.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,13); ++ExeCount; } #else #define REPORT {} #endif /******************************** Quick sort ********************************/ // Quicksort. // Essentially the method described in Sedgewick s algorithms in C++ // My version is still partially recursive, unlike Segewick s, but the // smallest segment of each split is used in the recursion, so it should // not overlead the stack. // If the process does not seems to be converging an exception is thrown. #define DoSimpleSort 17 // when to switch to insert sort #define MaxDepth 50 // maximum recursion depth static void MyQuickSortDescending(Real* first, Real* last, int depth); static void InsertionSortDescending(Real* first, const int length, int guard); static Real SortThreeDescending(Real* a, Real* b, Real* c); static void MyQuickSortAscending(Real* first, Real* last, int depth); static void InsertionSortAscending(Real* first, const int length, int guard); void SortDescending(GeneralMatrix& GM) { REPORT Tracer et("QuickSortDescending"); Real* data = GM.Store(); int max = GM.Storage(); if (max > DoSimpleSort) MyQuickSortDescending(data, data + max - 1, 0); InsertionSortDescending(data, max, DoSimpleSort); } static Real SortThreeDescending(Real* a, Real* b, Real* c) { // sort *a, *b, *c; return *b; optimise for already sorted if (*a >= *b) { if (*b >= *c) { REPORT return *b; } else if (*a >= *c) { REPORT Real x = *c; *c = *b; *b = x; return x; } else { REPORT Real x = *a; *a = *c; *c = *b; *b = x; return x; } } else if (*c >= *b) { REPORT Real x = *c; *c = *a; *a = x; return *b; } else if (*a >= *c) { REPORT Real x = *a; *a = *b; *b = x; return x; } else { REPORT Real x = *c; *c = *a; *a = *b; *b = x; return x; } } static void InsertionSortDescending(Real* first, const int length, int guard) // guard gives the length of the sequence to scan to find first // element (eg = length) { REPORT if (length <= 1) return; // scan for first element Real* f = first; Real v = *f; Real* h = f; if (guard > length) { REPORT guard = length; } int i = guard - 1; while (i--) if (v < *(++f)) { v = *f; h = f; } *h = *first; *first = v; // do the sort i = length - 1; f = first; while (i--) { Real* g = f++; h = f; v = *h; while (*g < v) *h-- = *g--; *h = v; } } static void MyQuickSortDescending(Real* first, Real* last, int depth) { REPORT for (;;) { const int length = last - first + 1; if (length < DoSimpleSort) { REPORT return; } if (depth++ > MaxDepth) Throw(ConvergenceException("QuickSortDescending fails: ")); Real* centre = first + length/2; const Real test = SortThreeDescending(first, centre, last); Real* f = first; Real* l = last; for (;;) { while (*(++f) > test) {} while (*(--l) < test) {} if (l <= f) break; const Real temp = *f; *f = *l; *l = temp; } if (f > centre) { REPORT MyQuickSortDescending(l+1, last, depth); last = f-1; } else { REPORT MyQuickSortDescending(first, f-1, depth); first = l+1; } } } void SortAscending(GeneralMatrix& GM) { REPORT Tracer et("QuickSortAscending"); Real* data = GM.Store(); int max = GM.Storage(); if (max > DoSimpleSort) MyQuickSortAscending(data, data + max - 1, 0); InsertionSortAscending(data, max, DoSimpleSort); } static void InsertionSortAscending(Real* first, const int length, int guard) // guard gives the length of the sequence to scan to find first // element (eg guard = length) { REPORT if (length <= 1) return; // scan for first element Real* f = first; Real v = *f; Real* h = f; if (guard > length) { REPORT guard = length; } int i = guard - 1; while (i--) if (v > *(++f)) { v = *f; h = f; } *h = *first; *first = v; // do the sort i = length - 1; f = first; while (i--) { Real* g = f++; h = f; v = *h; while (*g > v) *h-- = *g--; *h = v; } } static void MyQuickSortAscending(Real* first, Real* last, int depth) { REPORT for (;;) { const int length = last - first + 1; if (length < DoSimpleSort) { REPORT return; } if (depth++ > MaxDepth) Throw(ConvergenceException("QuickSortAscending fails: ")); Real* centre = first + length/2; const Real test = SortThreeDescending(last, centre, first); Real* f = first; Real* l = last; for (;;) { while (*(++f) < test) {} while (*(--l) > test) {} if (l <= f) break; const Real temp = *f; *f = *l; *l = temp; } if (f > centre) { REPORT MyQuickSortAscending(l+1, last, depth); last = f-1; } else { REPORT MyQuickSortAscending(first, f-1, depth); first = l+1; } } } //********* sort diagonal matrix & rearrange matrix columns **************** // used by SVD // these are for sorting singular values - should be updated with faster // sorts that handle exchange of columns better // however time is probably not significant compared with SVD time void SortSV(DiagonalMatrix& D, Matrix& U, bool ascending) { REPORT Tracer trace("SortSV_DU"); int m = U.Nrows(); int n = U.Ncols(); if (n != D.Nrows()) Throw(IncompatibleDimensionsException(D,U)); Real* u = U.Store(); for (int i=0; i p) { k = j; p = D.element(j); } } } if (k != i) { D.element(k) = D.element(i); D.element(i) = p; int j = m; Real* uji = u + i; Real* ujk = u + k; if (j) for(;;) { p = *uji; *uji = *ujk; *ujk = p; if (!(--j)) break; uji += n; ujk += n; } } } } void SortSV(DiagonalMatrix& D, Matrix& U, Matrix& V, bool ascending) { REPORT Tracer trace("SortSV_DUV"); int mu = U.Nrows(); int mv = V.Nrows(); int n = D.Nrows(); if (n != U.Ncols()) Throw(IncompatibleDimensionsException(D,U)); if (n != V.Ncols()) Throw(IncompatibleDimensionsException(D,V)); Real* u = U.Store(); Real* v = V.Store(); for (int i=0; i p) { k = j; p = D.element(j); } } } if (k != i) { D.element(k) = D.element(i); D.element(i) = p; Real* uji = u + i; Real* ujk = u + k; Real* vji = v + i; Real* vjk = v + k; int j = mu; if (j) for(;;) { p = *uji; *uji = *ujk; *ujk = p; if (!(--j)) break; uji += n; ujk += n; } j = mv; if (j) for(;;) { p = *vji; *vji = *vjk; *vjk = p; if (!(--j)) break; vji += n; vjk += n; } } } } #ifdef use_namespace } #endif newmat-1.10.4/submat.cpp0000644001161000116100000002650207423655112013305 0ustar rzrrzr//$$ submat.cpp submatrices // Copyright (C) 1991,2,3,4: R B Davies #include "include.h" #include "newmat.h" #include "newmatrc.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,11); ++ExeCount; } #else #define REPORT {} #endif /****************************** submatrices *********************************/ #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix& BaseMatrix::SubMatrix(int first_row, int last_row, int first_col, int last_col) const #else GetSubMatrix BaseMatrix::SubMatrix(int first_row, int last_row, int first_col, int last_col) const #endif { REPORT Tracer tr("SubMatrix"); int a = first_row - 1; int b = last_row - first_row + 1; int c = first_col - 1; int d = last_col - first_col + 1; if (a<0 || b<0 || c<0 || d<0) Throw(SubMatrixDimensionException()); // allow zero rows or columns #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix* x = new GetSubMatrix(this, a, b, c, d, false); MatrixErrorNoSpace(x); return *x; #else return GetSubMatrix(this, a, b, c, d, false); #endif } #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix& BaseMatrix::SymSubMatrix(int first_row, int last_row) const #else GetSubMatrix BaseMatrix::SymSubMatrix(int first_row, int last_row) const #endif { REPORT Tracer tr("SubMatrix(symmetric)"); int a = first_row - 1; int b = last_row - first_row + 1; if (a<0 || b<0) Throw(SubMatrixDimensionException()); // allow zero rows or columns #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix* x = new GetSubMatrix(this, a, b, a, b, true); MatrixErrorNoSpace(x); return *x; #else return GetSubMatrix( this, a, b, a, b, true); #endif } #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix& BaseMatrix::Row(int first_row) const #else GetSubMatrix BaseMatrix::Row(int first_row) const #endif { REPORT Tracer tr("SubMatrix(row)"); int a = first_row - 1; if (a<0) Throw(SubMatrixDimensionException()); #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix* x = new GetSubMatrix(this, a, 1, 0, -1, false); MatrixErrorNoSpace(x); return *x; #else return GetSubMatrix(this, a, 1, 0, -1, false); #endif } #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix& BaseMatrix::Rows(int first_row, int last_row) const #else GetSubMatrix BaseMatrix::Rows(int first_row, int last_row) const #endif { REPORT Tracer tr("SubMatrix(rows)"); int a = first_row - 1; int b = last_row - first_row + 1; if (a<0 || b<0) Throw(SubMatrixDimensionException()); // allow zero rows or columns #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix* x = new GetSubMatrix(this, a, b, 0, -1, false); MatrixErrorNoSpace(x); return *x; #else return GetSubMatrix(this, a, b, 0, -1, false); #endif } #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix& BaseMatrix::Column(int first_col) const #else GetSubMatrix BaseMatrix::Column(int first_col) const #endif { REPORT Tracer tr("SubMatrix(column)"); int c = first_col - 1; if (c<0) Throw(SubMatrixDimensionException()); #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix* x = new GetSubMatrix(this, 0, -1, c, 1, false); MatrixErrorNoSpace(x); return *x; #else return GetSubMatrix(this, 0, -1, c, 1, false); #endif } #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix& BaseMatrix::Columns(int first_col, int last_col) const #else GetSubMatrix BaseMatrix::Columns(int first_col, int last_col) const #endif { REPORT Tracer tr("SubMatrix(columns)"); int c = first_col - 1; int d = last_col - first_col + 1; if (c<0 || d<0) Throw(SubMatrixDimensionException()); // allow zero rows or columns #ifdef TEMPS_DESTROYED_QUICKLY GetSubMatrix* x = new GetSubMatrix(this, 0, -1, c, d, false); MatrixErrorNoSpace(x); return *x; #else return GetSubMatrix(this, 0, -1, c, d, false); #endif } void GetSubMatrix::SetUpLHS() { REPORT Tracer tr("SubMatrix(LHS)"); const BaseMatrix* bm1 = bm; GeneralMatrix* gm1 = ((BaseMatrix*&)bm)->Evaluate(); if ((BaseMatrix*)gm1!=bm1) Throw(ProgramException("Invalid LHS")); if (row_number < 0) row_number = gm1->Nrows(); if (col_number < 0) col_number = gm1->Ncols(); if (row_skip+row_number > gm1->Nrows() || col_skip+col_number > gm1->Ncols()) Throw(SubMatrixDimensionException()); } void GetSubMatrix::operator<<(const BaseMatrix& bmx) { REPORT Tracer tr("SubMatrix(<<)"); GeneralMatrix* gmx = 0; Try { SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) Throw(IncompatibleDimensionsException()); MatrixRow mrx(gmx, LoadOnEntry); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Copy(mrx); mr.Next(); mrx.Next(); } gmx->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif } CatchAll { if (gmx) gmx->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } } void GetSubMatrix::operator=(const BaseMatrix& bmx) { REPORT Tracer tr("SubMatrix(=)"); GeneralMatrix* gmx = 0; // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) Throw(IncompatibleDimensionsException()); LoadAndStoreFlag lasf = ( row_skip == col_skip && gm->Type().IsSymmetric() && gmx->Type().IsSymmetric() ) ? LoadOnEntry+DirectPart : LoadOnEntry; MatrixRow mrx(gmx, lasf); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.CopyCheck(mrx); mr.Next(); mrx.Next(); } gmx->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif } CatchAll { if (gmx) gmx->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } } void GetSubMatrix::operator<<(const Real* r) { REPORT Tracer tr("SubMatrix(< gm->Nrows() || col_skip+col_number > gm->Ncols()) Throw(SubMatrixDimensionException()); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Copy(r); mr.Next(); } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif } void GetSubMatrix::operator=(Real r) { REPORT Tracer tr("SubMatrix(=Real)"); SetUpLHS(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Copy(r); mr.Next(); } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif } void GetSubMatrix::Inject(const GeneralMatrix& gmx) { REPORT Tracer tr("SubMatrix(inject)"); SetUpLHS(); if (row_number != gmx.Nrows() || col_number != gmx.Ncols()) Throw(IncompatibleDimensionsException()); MatrixRow mrx((GeneralMatrix*)(&gmx), LoadOnEntry); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Inject(mrx); mr.Next(); mrx.Next(); } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif } void GetSubMatrix::operator+=(const BaseMatrix& bmx) { REPORT Tracer tr("SubMatrix(+=)"); GeneralMatrix* gmx = 0; // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) Throw(IncompatibleDimensionsException()); MatrixRow mrx(gmx, LoadOnEntry); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Check(mrx); // check for loss of info sub.Add(mrx); mr.Next(); mrx.Next(); } gmx->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif } CatchAll { if (gmx) gmx->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } } void GetSubMatrix::operator-=(const BaseMatrix& bmx) { REPORT Tracer tr("SubMatrix(-=)"); GeneralMatrix* gmx = 0; // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); gmx = ((BaseMatrix&)bmx).Evaluate(); if (row_number != gmx->Nrows() || col_number != gmx->Ncols()) Throw(IncompatibleDimensionsException()); MatrixRow mrx(gmx, LoadOnEntry); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Check(mrx); // check for loss of info sub.Sub(mrx); mr.Next(); mrx.Next(); } gmx->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif } CatchAll { if (gmx) gmx->tDelete(); #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } } void GetSubMatrix::operator+=(Real r) { REPORT Tracer tr("SubMatrix(+= or -= Real)"); // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Check(); // check for loss of info sub.Add(r); mr.Next(); } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif } CatchAll { #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } } void GetSubMatrix::operator*=(Real r) { REPORT Tracer tr("SubMatrix(*= or /= Real)"); // MatrixConversionCheck mcc; // Check for loss of info Try { SetUpLHS(); MatrixRow mr(gm, LoadOnEntry+StoreOnExit+DirectPart, row_skip); // do need LoadOnEntry MatrixRowCol sub; int i = row_number; while (i--) { mr.SubRowCol(sub, col_skip, col_number); // put values in sub sub.Multiply(r); mr.Next(); } #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif } CatchAll { #ifdef TEMPS_DESTROYED_QUICKLY delete this; #endif ReThrow; } } #ifdef use_namespace } #endif newmat-1.10.4/svd.cpp0000644001161000116100000001501307414475354012611 0ustar rzrrzr//$$svd.cpp singular value decomposition // Copyright (C) 1991,2,3,4,5: R B Davies // Updated 17 July, 1995 #define WANT_MATH #include "include.h" #include "newmatap.h" #include "newmatrm.h" #include "precisio.h" #ifdef use_namespace namespace NEWMAT { #endif #ifdef DO_REPORT #define REPORT { static ExeCounter ExeCount(__LINE__,15); ++ExeCount; } #else #define REPORT {} #endif static Real pythag(Real f, Real g, Real& c, Real& s) // return z=sqrt(f*f+g*g), c=f/z, s=g/z // set c=1,s=0 if z==0 // avoid floating point overflow or divide by zero { if (f==0 && g==0) { c=1.0; s=0.0; return 0.0; } Real af = f>=0 ? f : -f; Real ag = g>=0 ? g : -g; if (ag= no. Cols", A)); if (withV && &U == &V) Throw(ProgramException("Need different matrices for U and V", U, V)); U = A; Real g = 0.0; Real f,h; Real x = 0.0; int i; RowVector E(n); RectMatrixRow EI(E,0); Q.ReSize(n); RectMatrixCol UCI(U,0); RectMatrixRow URI(U,0,1,n-1); if (n) for (i=0;;) { EI.First() = g; Real ei = g; EI.Right(); Real s = UCI.SumSquare(); if (s=0; i--) { VCI.Left(); if (g!=0.0) { VCI.Divide(URI, URI.First()*g); int j = n-i; RectMatrixCol VCJ = VCI; while (--j) { VCJ.Right(); VCJ.AddScaled( VCI, (URI*VCJ) ); } } VCI.Zero(); VCI.Up(); VCI.First() = 1.0; g=E.element(i); if (i==0) break; URI.UpDiag(); } } if (withU) { REPORT for (i=n-1; i>=0; i--) { g = Q.element(i); URI.Reset(U,i,i+1,n-i-1); URI.Zero(); if (g!=0.0) { h=UCI.First()*g; int j=n-i; RectMatrixCol UCJ = UCI; while (--j) { UCJ.Right(); UCI.Down(); UCJ.Down(); Real s = UCI*UCJ; UCI.Up(); UCJ.Up(); UCJ.AddScaled(UCI,s/h); } UCI.Divide(g); } else UCI.Zero(); UCI.First() += 1.0; if (i==0) break; UCI.UpDiag(); } } eps *= x; for (int k=n-1; k>=0; k--) { Real z = -FloatingPointPrecision::Maximum(); // to keep Gnu happy Real y; int limit = 50; int l = 0; while (limit--) { Real c, s; int i; int l1=k; bool tfc=false; for (l=k; l>=0; l--) { // if (fabs(E.element(l))<=eps) goto test_f_convergence; if (fabs(E.element(l))<=eps) { REPORT tfc=true; break; } if (fabs(Q.element(l-1))<=eps) { REPORT l1=l; break; } REPORT } if (!tfc) { REPORT l=l1; l1=l-1; s = -1.0; c = 0.0; for (i=l; i<=k; i++) { f = - s * E.element(i); E.element(i) *= c; // if (fabs(f)<=eps) goto test_f_convergence; if (fabs(f)<=eps) { REPORT break; } g = Q.element(i); h = pythag(g,f,c,s); Q.element(i) = h; if (withU) { REPORT RectMatrixCol UCI(U,i); RectMatrixCol UCJ(U,l1); ComplexScale(UCJ, UCI, c, s); } } } // test_f_convergence: z = Q.element(k); if (l==k) goto convergence; z = Q.element(k); if (l==k) { REPORT break; } x = Q.element(l); y = Q.element(k-1); g = E.element(k-1); h = E.element(k); f = ((y-z)*(y+z) + (g-h)*(g+h)) / (2*h*y); if (f>1) { REPORT g = f * sqrt(1 + square(1/f)); } else if (f<-1) { REPORT g = -f * sqrt(1 + square(1/f)); } else { REPORT g = sqrt(f*f + 1); } { REPORT f = ((x-z)*(x+z) + h*(y / ((f<0.0) ? f-g : f+g)-h)) / x; } c = 1.0; s = 1.0; for (i=l+1; i<=k; i++) { g = E.element(i); y = Q.element(i); h = s*g; g *= c; z = pythag(f,h,c,s); E.element(i-1) = z; f = x*c + g*s; g = -x*s + g*c; h = y*s; y *= c; if (withV) { REPORT RectMatrixCol VCI(V,i); RectMatrixCol VCJ(V,i-1); ComplexScale(VCI, VCJ, c, s); } z = pythag(f,h,c,s); Q.element(i-1) = z; f = c*g + s*y; x = -s*g + c*y; if (withU) { REPORT RectMatrixCol UCI(U,i); RectMatrixCol UCJ(U,i-1); ComplexScale(UCI, UCJ, c, s); } } E.element(l) = 0.0; E.element(k) = f; Q.element(k) = x; } if (l!=k) { Throw(ConvergenceException(A)); } // convergence: if (z < 0.0) { REPORT Q.element(k) = -z; if (withV) { RectMatrixCol VCI(V,k); VCI.Negate(); } } } if (withU & withV) SortSV(Q, U, V); else if (withU) SortSV(Q, U); else if (withV) SortSV(Q, V); else SortDescending(Q); } void SVD(const Matrix& A, DiagonalMatrix& D) { REPORT Matrix U; SVD(A, D, U, U, false, false); } #ifdef use_namespace } #endif newmat-1.10.4/test_exc.cpp0000644001161000116100000001447710406436572013642 0ustar rzrrzr#define WANT_STREAM #include "newmatap.h" #include "newmatio.h" // to help namespace with VC++ 5 #ifdef use_namespace using namespace RBD_LIBRARIES; #endif //#include // if you want to use set_terminate /**************************** test exceptions ******************************/ int main() { // activate the next expression if you want to use compiler supported // exceptions and you want Terminate to catch uncaught exceptions // set_terminate(Terminate); Real* s1; Real* s2; Real* s3; Real* s4; // Forces cout to allocate memory at beginning cout << "\nThis tests the exception system, so you will get\n" << "a long list of error messages\n\n"; cout << "\nPrint a real number (may help lost memory test): " << 3.14159265 << "\n"; // Throw exception to set up exception buffer Try { Throw(BaseException("Just a dummy\n")); } CatchAll {}; { Matrix A1(40,200); s1 = A1.Store(); } { Matrix A1(1,1); s3 = A1.Store(); } { Tracer et("Test"); Try { Tracer et("Try block"); cout << "-----------------------------------------\n\n"; Matrix A(2,3), B(4,5); A = 1; B = 2; cout << "Incompatible dimensions\n"; et.ReName("Block A"); Try { Matrix C = A + B; } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Bad index\n"; et.ReName("Block B"); Try { Real f = A(3,3); cout << f << endl; } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Illegal conversion\n"; et.ReName("Block C"); Try { UpperTriangularMatrix U = A; } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Invert non-square matrix - 1\n"; et.ReName("Block D"); Try { CroutMatrix X = A; } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Invert non-square matrix - 2\n"; et.ReName("Block E"); Try { Matrix X = A.i(); } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Non 1x1 matrix to scalar\n"; et.ReName("Block F"); Try { Real f = A.AsScalar(); cout << f << endl; } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Matrix to vector\n"; et.ReName("Block G"); Try { ColumnVector CV = A;} CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Invert singular matrix\n"; et.ReName("Block H"); Try { Matrix X(2,2); X<<1<<2<<2<<4; X = X.i(); } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "SubMatrix error\n"; et.ReName("Block I"); Try { Matrix X = A.Row(3); } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "SubMatrix error\n"; et.ReName("Block J"); Try { Matrix X = A.Row(0); } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Cholesky error\n"; et.ReName("Block K"); Try { SymmetricMatrix SM(50); SM = 10; LowerTriangularMatrix L = Cholesky(SM); } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Inequality error\n"; et.ReName("Block L"); Try { Matrix A(10,10), B(10,10); A = 10; B = 20; if ( A < B) A = B; } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Maximum of empty matrix\n"; et.ReName("Block M"); Try { Matrix A(10,20); A = 5; Matrix B=A.Rows(6,5); MaximumAbsoluteValue(B); } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Incorrectly ReSizing band matrix\n"; et.ReName("Block N"); Try { BandMatrix A(20,5,3); A = 5; UpperBandMatrix B; B.ReSize(A); } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "Incorrectly ReSizing symmetric band matrix\n"; et.ReName("Block M"); Try { BandMatrix A(20,5,3); A = 5; SymmetricBandMatrix B; B.ReSize(A); } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; cout << "ReSize CroutMatrix\n"; et.ReName("Block O"); Try { Matrix A(3,3); A = 0; A(1,1) = A(2,2) = A(3,3) = 1; CroutMatrix B = A;; B.ReSize(A); } CatchAll { cout << BaseException::what() << endl; } cout << "-----------------------------------------\n\n"; } CatchAll { cout << "\nException generated in test program\n\n"; } } cout << "\nEnd test\n"; { Matrix A1(40,200); s2 = A1.Store(); } cout << "\n(The following memory checks are probably not valid with all\n"; cout << "compilers - see documentation)\n"; cout << "\nChecking for lost memory: " << (unsigned long)s1 << " " << (unsigned long)s2 << " "; if (s1 != s2) cout << " - error\n"; else cout << " - ok\n"; { Matrix A1(1,1); s4 = A1.Store(); } cout << "\nChecking for lost memory: " << (unsigned long)s3 << " " << (unsigned long)s4 << " "; if (s3 != s4) cout << " - error\n\n"; else cout << " - ok\n\n"; #ifdef DO_FREE_CHECK FreeCheck::Status(); #endif // Throw(Runtime_error("Exception outside try block")); return 0; } newmat-1.10.4/test_exc.txt0000644001161000116100000000772207550774340013676 0ustar rzrrzr This tests the exception system, so you will get a long list of error messages Print a real number (may help lost memory test): 3.14159 ----------------------------------------- Incompatible dimensions An exception has been thrown Logic error:- detected by Newmat: incompatible dimensions MatrixType = Rect # Rows = 2; # Cols = 3 MatrixType = Rect # Rows = 4; # Cols = 5 Trace: AddedMatrix::Evaluate; Block A; Test. ----------------------------------------- Bad index An exception has been thrown Logic error:- detected by Newmat: index error: requested indices = 3, 3 MatrixType = Rect # Rows = 2; # Cols = 3 Trace: Block B; Test. ----------------------------------------- Illegal conversion An exception has been thrown Logic error:- detected by Newmat: Illegal Conversion MatrixTypes = Rect ; UT Trace: Block C; Test. ----------------------------------------- Invert non-square matrix - 1 An exception has been thrown Logic error:- detected by Newmat: matrix is not square MatrixType = Rect # Rows = 2; # Cols = 3 Trace: CroutMatrix; Block D; Test. ----------------------------------------- Invert non-square matrix - 2 An exception has been thrown Logic error:- detected by Newmat: matrix is not square MatrixType = Rect # Rows = 2; # Cols = 3 Trace: GeneralSolvI; InvertedMatrix::Evaluate; Block E; Test. ----------------------------------------- Non 1x1 matrix to scalar An exception has been thrown Logic error:- detected by Newmat: Cannot convert to scalar MatrixType = Rect # Rows = 2; # Cols = 3 Trace: AsScalar; Block F; Test. ----------------------------------------- Matrix to vector An exception has been thrown Logic error:- detected by Newmat: cannot convert matrix to vector MatrixType = Rect # Rows = 2; # Cols = 3 Trace: ColumnVector; Block G; Test. ----------------------------------------- Invert singular matrix An exception has been thrown Runtime error:- detected by Newmat: matrix is singular MatrixType = Crout # Rows = 2; # Cols = 2 Trace: Crout(lubksb); GeneralSolvI; InvertedMatrix::Evaluate; Block H; Test. ----------------------------------------- SubMatrix error An exception has been thrown Logic error:- detected by Newmat: incompatible submatrix dimension Trace: SubMatrix(evaluate); Block I; Test. ----------------------------------------- SubMatrix error An exception has been thrown Logic error:- detected by Newmat: incompatible submatrix dimension Trace: SubMatrix(row); Block J; Test. ----------------------------------------- Cholesky error An exception has been thrown Runtime error:- detected by Newmat: matrix not positive definite MatrixType = Sym # Rows = 50; # Cols = 50 Trace: Cholesky; Block K; Test. ----------------------------------------- Inequality error An exception has been thrown Logic error:- detected by Newmat: inequalities not defined for matrices Trace: Block L; Test. ----------------------------------------- Maximum of empty matrix An exception has been thrown Logic error:- detected by Newmat: Maximum or minimum of null matrix Trace: Block M; Test. ----------------------------------------- Incorrectly ReSizing band matrix An exception has been thrown Logic error:- detected by Newmat: UpperBandMatrix with non-zero lower band Trace: UpperBandMatrix::ReSize; Block N; Test. ----------------------------------------- Incorrectly ReSizing symmetric band matrix An exception has been thrown Logic error:- detected by Newmat: Upper and lower band-widths not equal Trace: SymmetricBandMatrix::ReSize(GM); Block M; Test. ----------------------------------------- ReSize CroutMatrix An exception has been thrown Logic error:- detected by Newmat: ReSize not defined for this type of matrix Trace: GeneralMatrix::ReSize(GM); Block O; Test. ----------------------------------------- End test (The following memory checks are probably not valid with all compilers - see documentation) Checking for lost memory: 8142064 8142064 - ok Checking for lost memory: 8142064 8142064 - ok newmat-1.10.4/tmt.cpp0000644001161000116100000002424210407112741012605 0ustar rzrrzr#define WANT_STREAM #include "include.h" #include "newmat.h" #include "tmt.h" #ifdef use_namespace //using namespace NEWMAT; namespace NEWMAT { #endif /**************************** test program ******************************/ class PrintCounter { int count; const char* s; public: ~PrintCounter(); PrintCounter(const char * sx) : count(0), s(sx) {} void operator++() { count++; } }; PrintCounter PCZ("Number of non-zero matrices (should be 1) = "); PrintCounter PCN("Number of matrices tested = "); PrintCounter::~PrintCounter() { cout << s << count << "\n"; } void Print(const Matrix& X) { ++PCN; cout << "\nMatrix type: " << X.Type().Value() << " ("; cout << X.Nrows() << ", "; cout << X.Ncols() << ")\n\n"; if (X.IsZero()) { cout << "All elements are zero\n" << flush; return; } int nr=X.Nrows(); int nc=X.Ncols(); for (int i=1; i<=nr; i++) { for (int j=1; j<=nc; j++) cout << X(i,j) << "\t"; cout << "\n"; } cout << flush; ++PCZ; } void Print(const UpperTriangularMatrix& X) { ++PCN; cout << "\nMatrix type: " << X.Type().Value() << " ("; cout << X.Nrows() << ", "; cout << X.Ncols() << ")\n\n"; if (X.IsZero()) { cout << "All elements are zero\n" << flush; return; } int nr=X.Nrows(); int nc=X.Ncols(); for (int i=1; i<=nr; i++) { int j; for (j=1; j -c)) A(i,j) = 0.0; } } } void Clean(DiagonalMatrix& A, Real c) { int nr = A.Nrows(); for (int i=1; i<=nr; i++) { Real a = A(i,i); if ((a < c) && (a > -c)) A(i,i) = 0.0; } } void PentiumCheck(Real N, Real D) { Real R = N / D; R = R * D - N; if ( R > 1 || R < -1) cout << "Pentium error detected: % error = " << 100 * R / N << "\n"; } #ifdef use_namespace } using namespace NEWMAT; #endif //*************************** main program ********************************** void TestTypeAdd(); // test + void TestTypeMult(); // test * void TestTypeConcat(); // test | void TestTypeSP(); // test SP void TestTypeKP(); // test KP void TestTypeOrder(); // test >= int main() { Real* s1; Real* s2; Real* s3; Real* s4; cout << "\nBegin test\n"; // Forces cout to allocate memory at beginning cout << "Now print a real number: " << 3.14159265 << endl; // Throw exception to set up exception buffer #ifndef DisableExceptions Try { Throw(BaseException("Just a dummy\n")); } CatchAll {} #else cout << "Not doing exceptions\n"; #endif { Matrix A1(40,200); s1 = A1.Store(); } { Matrix A1(1,1); s3 = A1.Store(); } { Tracer et("Matrix test program"); Matrix A(25,150); { int i; RowVector A(8); for (i=1;i<=7;i++) A(i)=0.0; A(8)=1.0; Print(A); } cout << "\n"; TestTypeAdd(); TestTypeMult(); TestTypeConcat(); TestTypeSP(); TestTypeKP(); TestTypeOrder(); Try { trymat1(); trymat2(); trymat3(); trymat4(); trymat5(); trymat6(); trymat7(); trymat8(); trymat9(); trymata(); trymatb(); trymatc(); trymatd(); trymate(); trymatf(); trymatg(); trymath(); trymati(); trymatj(); trymatk(); trymatl(); trymatm(); cout << "\nEnd of tests\n"; } CatchAll { cout << "\nTest program fails - exception generated\n\n"; cout << BaseException::what(); } } { Matrix A1(40,200); s2 = A1.Store(); } cout << "\n(The following memory checks are probably not valid with all\n"; cout << "compilers - see documentation)\n"; cout << "\nChecking for lost memory: " << (unsigned long)s1 << " " << (unsigned long)s2 << " "; if (s1 != s2) cout << " - error\n"; else cout << " - ok\n"; { Matrix A1(1,1); s4 = A1.Store(); } cout << "\nChecking for lost memory: " << (unsigned long)s3 << " " << (unsigned long)s4 << " "; if (s3 != s4) cout << " - error\n\n"; else cout << " - ok\n\n"; // check for Pentium bug PentiumCheck(4195835L,3145727L); PentiumCheck(5244795L,3932159L); #ifdef DO_FREE_CHECK FreeCheck::Status(); #endif return 0; } //************************ test type manipulation **************************/ // These functions may cause problems for Glockenspiel 2.0c; they are used // only for testing so you can delete them void TestTypeAdd() { MatrixType list[10]; list[0] = MatrixType::UT; list[1] = MatrixType::LT; list[2] = MatrixType::Rt; list[3] = MatrixType::Sm; list[4] = MatrixType::Dg; list[5] = MatrixType::BM; list[6] = MatrixType::UB; list[7] = MatrixType::LB; list[8] = MatrixType::SB; list[9] = MatrixType::Id; cout << "+ "; int i; for (i=0; i= "; int i; for (i = 0; i=list[i]) ? "Yes " : "No "); cout << "\n"; } cout << "\n"; } newmat-1.10.4/tmt.h0000644001161000116100000000275510407112450012254 0ustar rzrrzr// definition file for test programs //#define DONT_DO_NRIC // activate if running a bounds checker #ifdef use_namespace //using namespace NEWMAT; namespace NEWMAT { #endif // print time between construction and destruction class time_lapse { double start_time; public: time_lapse(); ~time_lapse(); }; void Print(const Matrix& X); void Print(const UpperTriangularMatrix& X); void Print(const DiagonalMatrix& X); void Print(const SymmetricMatrix& X); void Print(const LowerTriangularMatrix& X); void Clean(Matrix&, Real); void Clean(DiagonalMatrix&, Real); #ifdef use_namespace } using namespace NEWMAT; #endif void trymat1(); void trymat2(); void trymat3(); void trymat4(); void trymat5(); void trymat6(); void trymat7(); void trymat8(); void trymat9(); void trymata(); void trymatb(); void trymatc(); void trymatd(); void trymate(); void trymatf(); void trymatg(); void trymath(); void trymati(); void trymatj(); void trymatk(); void trymatl(); void trymatm(); // body file: tmt.cpp // body file: tmt1.cpp // body file: tmt2.cpp // body file: tmt3.cpp // body file: tmt4.cpp // body file: tmt5.cpp // body file: tmt6.cpp // body file: tmt7.cpp // body file: tmt8.cpp // body file: tmt9.cpp // body file: tmta.cpp // body file: tmtb.cpp // body file: tmtc.cpp // body file: tmtd.cpp // body file: tmte.cpp // body file: tmtf.cpp // body file: tmtg.cpp // body file: tmth.cpp // body file: tmti.cpp // body file: tmtj.cpp // body file: tmtk.cpp // body file: tmtl.cpp // body file: tmtm.cpp newmat-1.10.4/tmt.txt0000644001161000116100000020533507647677530012676 0ustar rzrrzr Begin test Now print a real number: 3.14159 Matrix type: Rect (1, 8) 0 0 0 0 0 0 0 1 + UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Ident UT UT Rect Rect Rect UT Rect UT Rect Rect UT LT Rect LT Rect Rect LT Rect Rect LT Rect LT Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Sym Rect Rect Rect Sym Sym Rect Rect Rect Sym Sym Diag UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Diag Band Rect Rect Rect Rect Band Band Band Band Band Band UpBnd UT Rect Rect Rect UpBnd Band UpBnd Band Band UpBnd LwBnd Rect LT Rect Rect LwBnd Band Band LwBnd Band LwBnd SmBnd Rect Rect Rect Sym SmBnd Band Band Band SmBnd SmBnd Ident UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Ident * UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Ident UT UT Rect Rect Rect UT Rect UT Rect Rect UT LT Rect LT Rect Rect LT Rect Rect LT Rect LT Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Sym Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Diag UT LT Rect Rect Diag Band UpBnd LwBnd Band Diag Band Rect Rect Rect Rect Band Band Band Band Band Band UpBnd UT Rect Rect Rect UpBnd Band UpBnd Band Band UpBnd LwBnd Rect LT Rect Rect LwBnd Band Band LwBnd Band LwBnd SmBnd Rect Rect Rect Rect Band Band Band Band Band Band Ident UT LT Rect Rect Diag Band UpBnd LwBnd Band Ident | UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Ident UT Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect LT Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Sym Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Diag Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Band Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect UpBnd Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect LwBnd Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect SmBnd Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Ident Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect SP UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Ident UT UT Diag UT UT Diag UpBnd UpBnd Diag UpBnd Diag LT Diag LT LT LT Diag LwBnd Diag LwBnd LwBnd Diag Rect UT LT Rect Rect Diag Band UpBnd LwBnd Band Diag Sym UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Diag Diag Diag Diag Diag Diag Diag Diag Diag Diag Diag Diag Band UpBnd LwBnd Band Band Diag Band UpBnd LwBnd Band Diag UpBnd UpBnd Diag UpBnd UpBnd Diag UpBnd UpBnd Diag UpBnd Diag LwBnd Diag LwBnd LwBnd LwBnd Diag LwBnd Diag LwBnd LwBnd Diag SmBnd UpBnd LwBnd Band SmBnd Diag Band UpBnd LwBnd SmBnd Diag Ident Diag Diag Diag Diag Diag Diag Diag Diag Diag Ident KP UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Ident UT UT Rect Rect Rect UT Rect UT Rect Rect UT LT Rect LT Rect Rect LT Rect Rect LT Rect LT Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Rect Sym Rect Rect Rect Sym Sym Rect Rect Rect Sym Sym Diag UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Diag Band Rect Rect Rect Rect Band Band Band Band Band Band UpBnd UT Rect Rect Rect UpBnd Band UpBnd Band Band UpBnd LwBnd Rect LT Rect Rect LwBnd Band Band LwBnd Band LwBnd SmBnd Rect Rect Rect Sym SmBnd Band Band Band SmBnd SmBnd Ident UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Diag >= UT LT Rect Sym Diag Band UpBnd LwBnd SmBnd Ident UT Yes No Yes No No No No No No No LT No Yes Yes No No No No No No No Rect No No Yes No No No No No No No Sym No No Yes Yes No No No No No No Diag Yes Yes Yes Yes Yes Yes Yes Yes Yes No Band No No Yes No No Yes No No No No UpBnd Yes No Yes No No Yes Yes No No No LwBnd No Yes Yes No No Yes No Yes No No SmBnd No No Yes Yes No Yes No No Yes No Ident Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes * First test of Matrix package * Matrix test program Matrix type: LT (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: UT (9, 9) All elements are zero Matrix type: Rect (9, 9) All elements are zero Matrix type: Rect (10, 3) All elements are zero Matrix type: Rect (10, 3) All elements are zero Matrix type: Rect (10, 3) All elements are zero Matrix type: Rect (10, 3) All elements are zero Matrix type: Rect (10, 3) All elements are zero Matrix type: Rect (10, 3) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (20, 8) All elements are zero Matrix type: Rect (20, 6) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 20) All elements are zero Matrix type: Rect (20, 10) All elements are zero Matrix type: Rect (20, 10) All elements are zero Matrix type: Rect (10, 20) All elements are zero Matrix type: Rect (3, 3) All elements are zero * Second test of Matrix package * Matrix test program Matrix type: Rect (8, 10) All elements are zero Matrix type: Rect (8, 10) All elements are zero Matrix type: Rect (8, 10) All elements are zero Matrix type: Rect (8, 10) All elements are zero Matrix type: Rect (8, 10) All elements are zero Matrix type: Rect (100, 1) All elements are zero Matrix type: Rect (10, 1) All elements are zero Matrix type: Rect (20, 1) All elements are zero Matrix type: Rect (4, 7) All elements are zero Matrix type: Rect (4, 7) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (10, 20) All elements are zero Matrix type: Rect (0, 0) All elements are zero Matrix type: Rect (16, 1) All elements are zero Matrix type: Rect (0, 1) All elements are zero Matrix type: Rect (16, 1) All elements are zero Matrix type: Rect (1, 0) All elements are zero Matrix type: Rect (16, 1) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Diag (10, 10) All elements are zero Matrix type: Rect (8, 1) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (14, 1) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 20) All elements are zero Matrix type: Rect (20, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (4, 6) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Rect (3, 3) All elements are zero Matrix type: Rect (20, 20) All elements are zero * Third test of Matrix package * Matrix test program Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (6, 7) All elements are zero Matrix type: Rect (6, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Diag (6, 6) All elements are zero Matrix type: Diag (6, 6) All elements are zero Matrix type: Rect (3, 3) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (10, 1) All elements are zero Matrix type: Rect (1, 10) All elements are zero Matrix type: Diag (10, 10) All elements are zero Matrix type: Rect (19, 1) All elements are zero Matrix type: Rect (19, 1) All elements are zero Matrix type: Rect (3, 3) All elements are zero Matrix type: Rect (3, 3) All elements are zero Matrix type: Rect (3, 3) All elements are zero Matrix type: Rect (3, 3) All elements are zero Matrix type: Rect (4, 1) All elements are zero Matrix type: Rect (6, 1) All elements are zero Matrix type: Rect (6, 3) All elements are zero Matrix type: Rect (3, 3) All elements are zero * Fourth test of Matrix package * Matrix test program Matrix type: Rect (3, 10) All elements are zero Matrix type: Rect (3, 10) All elements are zero Matrix type: Rect (3, 3) All elements are zero Matrix type: Rect (10, 3) All elements are zero Matrix type: Rect (10, 3) All elements are zero Matrix type: Rect (10, 1) All elements are zero Matrix type: Rect (10, 3) All elements are zero Matrix type: Rect (5, 8) All elements are zero Matrix type: Rect (4, 5) All elements are zero Matrix type: Rect (4, 5) All elements are zero Matrix type: Rect (4, 5) All elements are zero Matrix type: Rect (4, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (4, 4) All elements are zero Matrix type: Diag (1, 1) All elements are zero Matrix type: Rect (2, 2) All elements are zero Matrix type: Diag (4, 4) All elements are zero Matrix type: Diag (4, 4) All elements are zero * Fifth test of Matrix package * Matrix test program Matrix type: Rect (6, 1) All elements are zero Matrix type: Rect (6, 1) All elements are zero Matrix type: Rect (6, 1) All elements are zero Matrix type: Rect (1, 6) All elements are zero Matrix type: Rect (1, 10) All elements are zero Matrix type: Rect (2, 3) All elements are zero Matrix type: Rect (3, 2) All elements are zero Matrix type: Rect (1, 10) All elements are zero Matrix type: Rect (10, 1) All elements are zero Matrix type: Rect (5, 6) All elements are zero Matrix type: Rect (31, 31) All elements are zero Matrix type: Rect (31, 31) All elements are zero Matrix type: Rect (31, 31) All elements are zero Matrix type: Rect (31, 31) All elements are zero Matrix type: Rect (31, 31) All elements are zero Matrix type: Rect (31, 31) All elements are zero Matrix type: Diag (31, 31) All elements are zero * Sixth test of Matrix package * Matrix test program Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: LT (5, 5) All elements are zero Matrix type: LT (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 10) All elements are zero Matrix type: Rect (5, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (15, 15) All elements are zero Matrix type: Rect (15, 15) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 2) All elements are zero Matrix type: Rect (1, 2) All elements are zero Matrix type: Rect (1, 2) All elements are zero Matrix type: Rect (1, 2) All elements are zero Matrix type: Rect (1, 2) All elements are zero Matrix type: Rect (1, 2) All elements are zero Matrix type: Rect (1, 2) All elements are zero Matrix type: Rect (1, 2) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 16) All elements are zero Matrix type: Rect (1, 16) All elements are zero Matrix type: Rect (1, 16) All elements are zero Matrix type: Rect (1, 16) All elements are zero Matrix type: Rect (1, 16) All elements are zero Matrix type: Rect (1, 16) All elements are zero Matrix type: Rect (1, 16) All elements are zero Matrix type: Rect (1, 16) All elements are zero Matrix type: Rect (1, 17) All elements are zero Matrix type: Rect (1, 17) All elements are zero Matrix type: Rect (1, 17) All elements are zero Matrix type: Rect (1, 17) All elements are zero Matrix type: Rect (1, 17) All elements are zero Matrix type: Rect (1, 17) All elements are zero Matrix type: Rect (1, 17) All elements are zero Matrix type: Rect (1, 17) All elements are zero Matrix type: Rect (1, 18) All elements are zero Matrix type: Rect (1, 18) All elements are zero Matrix type: Rect (1, 18) All elements are zero Matrix type: Rect (1, 18) All elements are zero Matrix type: Rect (1, 18) All elements are zero Matrix type: Rect (1, 18) All elements are zero Matrix type: Rect (1, 18) All elements are zero Matrix type: Rect (1, 18) All elements are zero Matrix type: Rect (1, 99) All elements are zero Matrix type: Rect (1, 99) All elements are zero Matrix type: Rect (1, 99) All elements are zero Matrix type: Rect (1, 99) All elements are zero Matrix type: Rect (1, 99) All elements are zero Matrix type: Rect (1, 99) All elements are zero Matrix type: Rect (1, 99) All elements are zero Matrix type: Rect (1, 99) All elements are zero Matrix type: Rect (1, 100) All elements are zero Matrix type: Rect (1, 100) All elements are zero Matrix type: Rect (1, 100) All elements are zero Matrix type: Rect (1, 100) All elements are zero Matrix type: Rect (1, 100) All elements are zero Matrix type: Rect (1, 100) All elements are zero Matrix type: Rect (1, 100) All elements are zero Matrix type: Rect (1, 100) All elements are zero Matrix type: Rect (1, 101) All elements are zero Matrix type: Rect (1, 101) All elements are zero Matrix type: Rect (1, 101) All elements are zero Matrix type: Rect (1, 101) All elements are zero Matrix type: Rect (1, 101) All elements are zero Matrix type: Rect (1, 101) All elements are zero Matrix type: Rect (1, 101) All elements are zero Matrix type: Rect (1, 101) All elements are zero * Seventh test of Matrix package * Matrix test program Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 121) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (11, 11) All elements are zero Matrix type: Rect (10, 1) All elements are zero * Eighth test of Matrix package * Matrix test program Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Diag (6, 6) All elements are zero Matrix type: Diag (6, 6) All elements are zero Matrix type: Diag (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: Rect (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: LT (4, 4) All elements are zero Matrix type: UT (4, 4) All elements are zero Matrix type: Diag (12, 12) All elements are zero Matrix type: Rect (10, 6) All elements are zero Matrix type: Rect (5, 9) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (6, 0) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero * Ninth test of Matrix package * Matrix test program Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 3) All elements are zero Matrix type: Rect (7, 3) All elements are zero Matrix type: Rect (3, 7) All elements are zero Matrix type: Diag (7, 7) All elements are zero Matrix type: Diag (7, 7) All elements are zero Matrix type: Diag (7, 7) All elements are zero Matrix type: Rect (18, 1) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (22, 1) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (4, 4) All elements are zero Matrix type: Rect (4, 4) All elements are zero * Tenth test of Matrix package * Matrix test program Matrix type: Rect (8, 6) All elements are zero Matrix type: Rect (8, 6) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (4, 2) All elements are zero Matrix type: Rect (4, 2) All elements are zero Matrix type: Rect (4, 2) All elements are zero Matrix type: UT (4, 4) All elements are zero Matrix type: Rect (4, 2) All elements are zero Matrix type: Rect (4, 4) All elements are zero Matrix type: Rect (4, 4) All elements are zero * Eleventh test of Matrix package * Matrix test program Matrix type: Rect (1, 10) All elements are zero Matrix type: Rect (1, 10) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 10) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (3, 4) All elements are zero Matrix type: Rect (6, 4) All elements are zero Matrix type: Rect (7, 6) All elements are zero Matrix type: Rect (3, 4) All elements are zero Matrix type: Rect (2, 3) All elements are zero * Twelfth test of Matrix package * Matrix test program Matrix type: Rect (15, 1) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (15, 1) All elements are zero Matrix type: Rect (3, 5) All elements are zero Matrix type: Rect (15, 1) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 5) All elements are zero Matrix type: Rect (7, 5) All elements are zero Matrix type: Rect (7, 5) All elements are zero Matrix type: UT (20, 20) All elements are zero Matrix type: UT (5, 5) All elements are zero Matrix type: UT (20, 20) All elements are zero Matrix type: UT (5, 5) All elements are zero Matrix type: Rect (8, 5) All elements are zero Matrix type: UT (20, 20) All elements are zero Matrix type: LT (20, 20) All elements are zero Matrix type: LT (5, 5) All elements are zero Matrix type: LT (20, 20) All elements are zero Matrix type: LT (5, 5) All elements are zero Matrix type: Rect (5, 8) All elements are zero Matrix type: LT (20, 20) All elements are zero Matrix type: Rect (20, 30) All elements are zero Matrix type: Rect (0, 0) All elements are zero Matrix type: Rect (20, 30) All elements are zero Matrix type: Rect (0, 0) All elements are zero Matrix type: Rect (20, 30) All elements are zero * Thirteenth test of Matrix package * Matrix test program Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (20, 5) All elements are zero Matrix type: Rect (20, 3) All elements are zero Matrix type: Rect (5, 3) All elements are zero Matrix type: Rect (3, 5) All elements are zero Matrix type: Rect (5, 1) All elements are zero Matrix type: Rect (1, 7) All elements are zero Matrix type: Rect (5, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (40, 40) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (40, 40) All elements are zero Matrix type: Rect (40, 40) All elements are zero Matrix type: Rect (40, 40) All elements are zero Matrix type: Rect (40, 40) All elements are zero Matrix type: Rect (40, 40) All elements are zero Matrix type: Rect (40, 40) All elements are zero Matrix type: Rect (4, 4) All elements are zero Matrix type: Rect (4, 4) All elements are zero Matrix type: Rect (50, 50) All elements are zero Matrix type: Rect (4, 4) All elements are zero * Fourteenth test of Matrix package * Matrix test program Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Rect (8, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Rect (8, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Rect (8, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Diag (8, 8) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Diag (8, 8) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (5, 5) All elements are zero Matrix type: Diag (8, 8) All elements are zero Matrix type: Diag (8, 8) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (21, 20) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Diag (21, 21) All elements are zero Matrix type: Rect (21, 21) All elements are zero Matrix type: Diag (21, 21) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Diag (21, 21) All elements are zero Matrix type: Rect (21, 21) All elements are zero Matrix type: Diag (21, 21) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Diag (21, 21) All elements are zero Matrix type: Diag (21, 21) All elements are zero Matrix type: Diag (30, 30) All elements are zero Matrix type: Rect (30, 30) All elements are zero Matrix type: Rect (30, 30) All elements are zero Matrix type: Rect (30, 30) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Diag (2, 2) All elements are zero Matrix type: Rect (2, 2) All elements are zero Matrix type: Rect (2, 2) All elements are zero Matrix type: Rect (2, 2) All elements are zero Matrix type: Diag (2, 2) All elements are zero Matrix type: Diag (2, 2) All elements are zero Matrix type: Rect (2, 2) All elements are zero Matrix type: Rect (2, 2) All elements are zero Matrix type: Rect (2, 2) All elements are zero Matrix type: Diag (2, 2) All elements are zero Matrix type: Diag (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (22, 20) All elements are zero Matrix type: Diag (10, 10) All elements are zero Matrix type: Diag (10, 10) All elements are zero Matrix type: Diag (10, 10) All elements are zero Matrix type: Diag (10, 10) All elements are zero Matrix type: Rect (6, 1) All elements are zero Matrix type: Sym (10, 10) All elements are zero Matrix type: Diag (9, 9) All elements are zero Matrix type: Diag (9, 9) All elements are zero Matrix type: Diag (9, 9) All elements are zero Matrix type: Rect (6, 1) All elements are zero Matrix type: Diag (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Diag (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (15, 15) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (15, 15) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (15, 15) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (15, 15) All elements are zero Matrix type: Diag (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero * Fifteenth test of Matrix package * Matrix test program Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (2048, 1) All elements are zero Matrix type: Rect (2048, 1) All elements are zero Matrix type: Rect (2000, 1) All elements are zero Matrix type: Rect (2000, 1) All elements are zero Matrix type: Rect (2187, 1) All elements are zero Matrix type: Rect (2187, 1) All elements are zero Matrix type: Rect (2310, 1) All elements are zero Matrix type: Rect (2310, 1) All elements are zero Matrix type: Rect (2401, 1) All elements are zero Matrix type: Rect (2401, 1) All elements are zero Matrix type: Rect (2197, 1) All elements are zero Matrix type: Rect (2197, 1) All elements are zero Matrix type: Rect (2021, 1) All elements are zero Matrix type: Rect (2021, 1) All elements are zero Matrix type: Rect (768, 1) All elements are zero Matrix type: Rect (768, 1) All elements are zero Matrix type: Rect (1280, 1) All elements are zero Matrix type: Rect (1280, 1) All elements are zero Matrix type: Rect (1792, 1) All elements are zero Matrix type: Rect (1792, 1) All elements are zero Matrix type: Rect (320, 1) All elements are zero Matrix type: Rect (320, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (50, 1) All elements are zero Matrix type: Rect (50, 1) All elements are zero Matrix type: Rect (98, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (22, 1) All elements are zero Matrix type: Rect (51, 1) All elements are zero Matrix type: Rect (51, 1) All elements are zero Matrix type: Rect (100, 1) All elements are zero Matrix type: Rect (1025, 1) All elements are zero Matrix type: Rect (1025, 1) All elements are zero Matrix type: Rect (2048, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (2000, 1) All elements are zero Matrix type: Rect (1226, 1) All elements are zero Matrix type: Rect (1226, 1) All elements are zero Matrix type: Rect (2450, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (13, 1) All elements are zero Matrix type: Rect (13, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (9, 1) All elements are zero Matrix type: Rect (9, 1) All elements are zero Matrix type: Rect (16, 1) All elements are zero Matrix type: Rect (16, 1) All elements are zero Matrix type: Rect (30, 1) All elements are zero Matrix type: Rect (30, 1) All elements are zero Matrix type: Rect (42, 1) All elements are zero Matrix type: Rect (42, 1) All elements are zero Matrix type: Rect (24, 1) All elements are zero Matrix type: Rect (24, 1) All elements are zero Matrix type: Rect (8, 1) All elements are zero Matrix type: Rect (8, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (48, 1) All elements are zero Matrix type: Rect (48, 1) All elements are zero Matrix type: Rect (4, 1) All elements are zero Matrix type: Rect (4, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (5, 1) All elements are zero Matrix type: Rect (5, 1) All elements are zero Matrix type: Rect (32, 1) All elements are zero Matrix type: Rect (32, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (26, 1) All elements are zero Matrix type: Rect (26, 1) All elements are zero Matrix type: Rect (32, 1) All elements are zero Matrix type: Rect (32, 1) All elements are zero Matrix type: Rect (18, 1) All elements are zero Matrix type: Rect (18, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (202, 1) All elements are zero Matrix type: Rect (202, 1) All elements are zero Matrix type: Rect (202, 1) All elements are zero Matrix type: Rect (202, 1) All elements are zero Matrix type: Rect (1000, 1) All elements are zero Matrix type: Rect (1000, 1) All elements are zero Matrix type: Rect (1000, 1) All elements are zero Matrix type: Rect (1000, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (275, 1) All elements are zero Matrix type: Rect (275, 1) All elements are zero Matrix type: Rect (275, 1) All elements are zero Matrix type: Rect (275, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (27, 1) All elements are zero Matrix type: Rect (27, 1) All elements are zero Matrix type: Rect (33, 1) All elements are zero Matrix type: Rect (33, 1) All elements are zero Matrix type: Rect (19, 1) All elements are zero Matrix type: Rect (19, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (2048, 1) All elements are zero Matrix type: Rect (2048, 1) All elements are zero Matrix type: Rect (2000, 1) All elements are zero Matrix type: Rect (2000, 1) All elements are zero Matrix type: Rect (2187, 1) All elements are zero Matrix type: Rect (2187, 1) All elements are zero Matrix type: Rect (2310, 1) All elements are zero Matrix type: Rect (2310, 1) All elements are zero Matrix type: Rect (2401, 1) All elements are zero Matrix type: Rect (2401, 1) All elements are zero Matrix type: Rect (2197, 1) All elements are zero Matrix type: Rect (2197, 1) All elements are zero Matrix type: Rect (2021, 1) All elements are zero Matrix type: Rect (2021, 1) All elements are zero Matrix type: Rect (768, 1) All elements are zero Matrix type: Rect (768, 1) All elements are zero Matrix type: Rect (1280, 1) All elements are zero Matrix type: Rect (1280, 1) All elements are zero Matrix type: Rect (1792, 1) All elements are zero Matrix type: Rect (1792, 1) All elements are zero Matrix type: Rect (320, 1) All elements are zero Matrix type: Rect (320, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (50, 1) All elements are zero Matrix type: Rect (50, 1) All elements are zero Matrix type: Rect (98, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (22, 1) All elements are zero Matrix type: Rect (51, 1) All elements are zero Matrix type: Rect (51, 1) All elements are zero Matrix type: Rect (100, 1) All elements are zero Matrix type: Rect (1025, 1) All elements are zero Matrix type: Rect (1025, 1) All elements are zero Matrix type: Rect (2048, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (2000, 1) All elements are zero Matrix type: Rect (1226, 1) All elements are zero Matrix type: Rect (1226, 1) All elements are zero Matrix type: Rect (2450, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (13, 1) All elements are zero Matrix type: Rect (13, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (12, 1) All elements are zero Matrix type: Rect (9, 1) All elements are zero Matrix type: Rect (9, 1) All elements are zero Matrix type: Rect (16, 1) All elements are zero Matrix type: Rect (16, 1) All elements are zero Matrix type: Rect (30, 1) All elements are zero Matrix type: Rect (30, 1) All elements are zero Matrix type: Rect (42, 1) All elements are zero Matrix type: Rect (42, 1) All elements are zero Matrix type: Rect (24, 1) All elements are zero Matrix type: Rect (24, 1) All elements are zero Matrix type: Rect (8, 1) All elements are zero Matrix type: Rect (8, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (40, 1) All elements are zero Matrix type: Rect (48, 1) All elements are zero Matrix type: Rect (48, 1) All elements are zero Matrix type: Rect (4, 1) All elements are zero Matrix type: Rect (4, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (5, 1) All elements are zero Matrix type: Rect (5, 1) All elements are zero Matrix type: Rect (32, 1) All elements are zero Matrix type: Rect (32, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (26, 1) All elements are zero Matrix type: Rect (26, 1) All elements are zero Matrix type: Rect (32, 1) All elements are zero Matrix type: Rect (32, 1) All elements are zero Matrix type: Rect (18, 1) All elements are zero Matrix type: Rect (18, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (202, 1) All elements are zero Matrix type: Rect (202, 1) All elements are zero Matrix type: Rect (202, 1) All elements are zero Matrix type: Rect (202, 1) All elements are zero Matrix type: Rect (1000, 1) All elements are zero Matrix type: Rect (1000, 1) All elements are zero Matrix type: Rect (1000, 1) All elements are zero Matrix type: Rect (1000, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (275, 1) All elements are zero Matrix type: Rect (275, 1) All elements are zero Matrix type: Rect (275, 1) All elements are zero Matrix type: Rect (275, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (1001, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (3, 1) All elements are zero Matrix type: Rect (27, 1) All elements are zero Matrix type: Rect (27, 1) All elements are zero Matrix type: Rect (33, 1) All elements are zero Matrix type: Rect (33, 1) All elements are zero Matrix type: Rect (19, 1) All elements are zero Matrix type: Rect (19, 1) All elements are zero * Sixteenth test of Matrix package * Matrix test program Matrix type: Rect (1, 7) All elements are zero Matrix type: Rect (1, 6) All elements are zero Matrix type: Rect (1, 6) All elements are zero Matrix type: Rect (1, 8) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (1, 3) All elements are zero Matrix type: Rect (1, 5) All elements are zero Matrix type: Rect (6, 1) All elements are zero * Seventeenth test of Matrix package * Matrix test program Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (6, 1) All elements are zero Matrix type: Rect (1, 7) All elements are zero Matrix type: Rect (80, 1) All elements are zero Matrix type: Rect (80, 1) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (80, 1) All elements are zero Matrix type: Rect (80, 1) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 8) All elements are zero Matrix type: Rect (8, 1) All elements are zero Matrix type: Rect (7, 1) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (7, 2) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Sym (20, 20) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (10, 10) All elements are zero Matrix type: Rect (6, 6) All elements are zero Matrix type: Rect (9, 2) All elements are zero Matrix type: Rect (1, 1) All elements are zero Matrix type: Rect (20, 30) All elements are zero Matrix type: UT (25, 25) All elements are zero Matrix type: LT (25, 25) All elements are zero Matrix type: Diag (25, 25) All elements are zero Matrix type: Sym (25, 25) All elements are zero Matrix type: Diag (25, 25) All elements are zero Matrix type: Rect (10, 1) All elements are zero Matrix type: Rect (1, 10) All elements are zero Matrix type: Rect (5, 5) All elements are zero Matrix type: Diag (4, 4) All elements are zero Matrix type: Rect (4, 4) All elements are zero Matrix type: Rect (1, 2) All elements are zero * Eighteenth test of Matrix package * Matrix test program Matrix type: Rect (23, 1) All elements are zero Matrix type: Rect (10, 20) All elements are zero * Nineteenth test of Matrix package * Matrix test program Matrix type: Rect (13, 7) All elements are zero Matrix type: Rect (13, 7) All elements are zero Matrix type: Rect (13, 7) All elements are zero Matrix type: Rect (13, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Diag (7, 7) All elements are zero Matrix type: Diag (7, 7) All elements are zero Matrix type: Diag (7, 7) All elements are zero Matrix type: Diag (7, 7) All elements are zero Matrix type: LT (7, 7) All elements are zero Matrix type: LT (7, 7) All elements are zero Matrix type: LT (7, 7) All elements are zero Matrix type: LT (7, 7) All elements are zero Matrix type: UT (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (25, 25) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (19, 19) All elements are zero Matrix type: Rect (2, 1) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero Matrix type: Rect (7, 7) All elements are zero * Twentieth test of Matrix package * Matrix test program C subscripts not enabled, not tested * Twenty first test of Matrix package * Matrix test program Matrix type: Rect (1, 28) All elements are zero * Twenty second test of Matrix package * Matrix test program Matrix type: Rect (8, 9) All elements are zero Matrix type: Diag (150, 150) All elements are zero Matrix type: UT (12, 12) All elements are zero Matrix type: Rect (12, 12) All elements are zero Matrix type: UT (12, 12) All elements are zero Matrix type: LT (12, 12) All elements are zero Matrix type: Rect (12, 12) All elements are zero Matrix type: UT (12, 12) All elements are zero Matrix type: LT (12, 12) All elements are zero Matrix type: Rect (24, 24) All elements are zero Matrix type: Rect (24, 24) All elements are zero Matrix type: Rect (24, 24) All elements are zero Matrix type: Rect (1, 4) All elements are zero Matrix type: UT (24, 24) All elements are zero Matrix type: LT (24, 24) All elements are zero Matrix type: Rect (12, 12) All elements are zero Matrix type: Rect (12, 12) All elements are zero Matrix type: Rect (12, 12) All elements are zero Matrix type: Rect (12, 12) All elements are zero Matrix type: Rect (12, 12) All elements are zero Matrix type: Rect (3, 3) All elements are zero Matrix type: Rect (1, 15) All elements are zero Matrix type: Rect (15, 1) All elements are zero Matrix type: Rect (15, 15) All elements are zero End of tests (The following memory checks are probably not valid with all compilers - see documentation) Checking for lost memory: 8797116 8797116 - ok Checking for lost memory: 8797116 8797116 - ok Number of matrices tested = 1215 Number of non-zero matrices (should be 1) = 1 newmat-1.10.4/tmt1.cpp0000644001161000116100000001434407205447576012713 0ustar rzrrzr #define WANT_STREAM #include "include.h" #include "newmat.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif /**************************** test program ******************************/ void trymat1() { // cout << "\nFirst test of Matrix package\n\n"; Tracer et("First test of Matrix package"); Tracer::PrintTrace(); { Tracer et1("Stage 1"); int i,j; LowerTriangularMatrix L(10); for (i=1;i<=10;i++) for (j=1;j<=i;j++) L(i,j)=2.0+i*i+j; SymmetricMatrix S(10); for (i=1;i<=10;i++) for (j=1;j<=i;j++) S(i,j)=i*j+1.0; SymmetricMatrix S1 = S / 2.0; S = S1 * 2.0; UpperTriangularMatrix U=L.t()*2.0; Print(LowerTriangularMatrix(L-U.t()*0.5)); DiagonalMatrix D(10); for (i=1;i<=10;i++) D(i,i)=(i-4)*(i-5)*(i-6); Matrix M=(S+U-D+L)*(L+U-D+S); DiagonalMatrix DD=D*D; LowerTriangularMatrix LD=L*D; // expressions split for Turbo C Matrix M1 = S*L + U*L - D*L + L*L + 10.0; { M1 = M1 + S*U + U*U - D*U + L*U - S*D; } { M1 = M1 - U*D + DD - LD + S*S; } { M1 = M1 + U*S - D*S + L*S - 10.0; } M=M1-M; Print(M); } { Tracer et1("Stage 2"); int i,j; LowerTriangularMatrix L(9); for (i=1;i<=9;i++) for (j=1;j<=i;j++) L(i,j)=1.0+j; UpperTriangularMatrix U1(9); for (j=1;j<=9;j++) for (i=1;i<=j;i++) U1(i,j)=1.0+i; LowerTriangularMatrix LX(9); for (i=1;i<=9;i++) for (j=1;j<=i;j++) LX(i,j)=1.0+i*i; UpperTriangularMatrix UX(9); for (j=1;j<=9;j++) for (i=1;i<=j;i++) UX(i,j)=1.0+j*j; { L=L+LX/0.5; L=L-LX*3.0; L=LX*2.0+L; U1=U1+UX*2.0; U1=U1-UX*3.0; U1=UX*2.0+U1; } SymmetricMatrix S(9); for (i=1;i<=9;i++) for (j=1;j<=i;j++) S(i,j)=i*i+j; { SymmetricMatrix S1 = S; S=S1+5.0; S=S-3.0; } DiagonalMatrix D(9); for (i=1;i<=9;i++) D(i,i)=S(i,i); UpperTriangularMatrix U=L.t()*2.0; { U1=U1*2.0 - U; Print(U1); L=L*2.0-D; U=U-D; } Matrix M=U+L; S=S*2.0; M=S-M; Print(M); } { Tracer et1("Stage 3"); int i,j; Matrix M(10,3), N(10,3); for (i = 1; i<=10; i++) for (j = 1; j<=3; j++) { M(i,j) = 2*i-j; N(i,j) = i*j + 20; } Matrix MN = M + N, M1; M1 = M; M1 += N; M1 -= MN; Print(M1); M1 = M; M1 += M1; M1 = M1 - M * 2; Print(M1); M1 = M; M1 += N * 2; M1 -= (MN + N); Print(M1); M1 = M; M1 -= M1; Print(M1); M1 = M; M1 -= MN + M1; M1 += N + M; Print(M1); M1 = M; M1 -= 5; M1 -= M; M1 *= 0.2; M1 = M1 + 1; Print(M1); Matrix NT = N.t(); M1 = M; M1 *= NT; M1 -= M * N.t(); Print(M1); M = M * M.t(); DiagonalMatrix D(10); D = 2; M1 = M; M1 += D; M1 -= M; M1 = M1 - D; Print(M1); M1 = M; M1 -= D; M1 -= M; M1 = M1 + D; Print(M1); M1 = M; M1 *= D; M1 /= 2; M1 -= M; Print(M1); SymmetricMatrix SM; SM << M; // UpperTriangularMatrix SM; SM << M; SM += 10; M1 = SM - M; M1 /=10; M1 = M1 - 1; Print(M1); } { Tracer et1("Stage 4"); int i,j; Matrix M(10,3), N(10,5); for (i = 1; i<=10; i++) for (j = 1; j<=3; j++) M(i,j) = 2*i-j; for (i = 1; i<=10; i++) for (j = 1; j<=5; j++) N(i,j) = i*j + 20; Matrix M1; M1 = M; M1 |= N; M1 &= N | M; M1 -= (M | N) & (N | M); Print(M1); M1 = M; M1 |= M1; M1 &= M1; M1 -= (M | M) & (M | M); Print(M1); } { Tracer et1("Stage 5"); int i,j; BandMatrix BM1(10,2,3), BM2(10,4,1); Matrix M1(10,10), M2(10,10); for (i=1;i<=10;i++) for (j=1;j<=10;j++) { M1(i,j) = 0.5*i+j*j-50; M2(i,j) = (i*101 + j*103) % 13; } BM1.Inject(M1); BM2.Inject(M2); BandMatrix BM = BM1; BM += BM2; Matrix M1X = BM1; Matrix M2X = BM2; Matrix MX = BM; MX -= M1X + M2X; Print(MX); MX = BM1; MX += BM2; MX -= M1X; MX -= M2X; Print(MX); SymmetricBandMatrix SM1; SM1 << BM1 * BM1.t(); SymmetricBandMatrix SM2; SM2 << BM2 * BM2.t(); SM1 *= 5.5; M1X *= M1X.t(); M1X *= 5.5; M2X *= M2X.t(); SM1 -= SM2; M1 = SM1 - M1X + M2X; Print(M1); M1 = BM1; BM1 *= SM1; M1 = M1 * SM1 - BM1; Print(M1); M1 = BM1; BM1 -= SM1; M1 = M1 - SM1 - BM1; Print(M1); M1 = BM1; BM1 += SM1; M1 = M1 + SM1 - BM1; Print(M1); } { Tracer et1("Stage 6"); int i,j; Matrix M(10,10), N(10,10); for (i = 1; i<=10; i++) for (j = 1; j<=10; j++) { M(i,j) = 2*i-j; N(i,j) = i*j + 20; } GenericMatrix GM = M; GM += N; Matrix M1 = GM - N - M; Print(M1); DiagonalMatrix D(10); D = 3; GM = D; GM += N; GM += M; GM += D; M1 = D*2 - GM + M + N; Print(M1); GM = D; GM *= 4; GM += 16; GM /= 8; GM -= 2; GM -= D / 2; M1 = GM; Print(M1); GM = D; GM *= M; GM *= N; GM /= 3; M1 = M*N - GM; Print(M1); GM = D; GM |= M; GM &= N | D; M1 = GM - ((D | M) & (N | D)); Print(M1); GM = M; M1 = M; GM += 5; GM *= 3; M *= 3; M += 15; M1 = GM - M; Print(M1); D.ReSize(10); for (i = 1; i<=10; i++) D(i) = i; M1 = D + 10; GM = D; GM += 10; M1 -= GM; Print(M1); GM = M; GM -= D; M1 = GM; GM = D; GM -= M; M1 += GM; Print(M1); GM = M; GM *= D; M1 = GM; GM = D; GM *= M.t(); M1 -= GM.t(); Print(M1); GM = M; GM += 2 * GM; GM -= 3 * M; M1 = GM; Print(M1); GM = M; GM |= GM; GM -= (M | M); M1 = GM; Print(M1); GM = M; GM &= GM; GM -= (M & M); M1 = GM; Print(M1); M1 = M; M1 = (M1.t() & M.t()) - (M | M).t(); Print(M1); M1 = M; M1 = (M1.t() | M.t()) - (M & M).t(); Print(M1); } { Tracer et1("Stage 7"); // test for bug in MS VC5 int n = 3; int k; int j; Matrix A(n,n), B(n,n); //first version - MS VC++ 5 mis-compiles if optimisation is on for (k=1; k<=n; k++) { for (j = 1; j <= n; j++) A(k,j) = ((k-1) * (2*j-1)); } //second version for (k=1; k<=n; k++) { const int k1 = k-1; // otherwise Visual C++ 5 fails for (j = 1; j <= n; j++) B(k,j) = (k1 * (2*j-1)); } if (A != B) { cout << "\nVisual C++ version 5 compiler error?"; cout << "\nTurn off optimisation"; } A -= B; Print(A); } // cout << "\nEnd of first test\n"; } newmat-1.10.4/tmt2.cpp0000644001161000116100000002175507424125156012706 0ustar rzrrzr //#define WANT_STREAM #include "include.h" #include "newmat.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif /**************************** test program ******************************/ void trymat2() { // cout << "\nSecond test of Matrix package\n\n"; Tracer et("Second test of Matrix package"); Tracer::PrintTrace(); int i,j; Matrix M(3,5); for (i=1; i<=3; i++) for (j=1; j<=5; j++) M(i,j) = 100*i + j; Matrix X(8,10); for (i=1; i<=8; i++) for (j=1; j<=10; j++) X(i,j) = 1000*i + 10*j; Matrix Y = X; Matrix Z = X; { X.SubMatrix(2,4,3,7) << M; } for (i=1; i<=3; i++) for (j=1; j<=5; j++) Y(i+1,j+2) = 100*i + j; Print(Matrix(X-Y)); Real a[15]; Real* r = a; for (i=1; i<=3; i++) for (j=1; j<=5; j++) *r++ = 100*i + j; { Z.SubMatrix(2,4,3,7) << a; } Print(Matrix(Z-Y)); { M=33; X.SubMatrix(2,4,3,7) << M; } { Z.SubMatrix(2,4,3,7) = 33; } Print(Matrix(Z-X)); for (i=1; i<=8; i++) for (j=1; j<=10; j++) X(i,j) = 1000*i + 10*j; Y = X; UpperTriangularMatrix U(5); for (i=1; i<=5; i++) for (j=i; j<=5; j++) U(i,j) = 100*i + j; { X.SubMatrix(3,7,5,9) << U; } for (i=1; i<=5; i++) for (j=i; j<=5; j++) Y(i+2,j+4) = 100*i + j; for (i=1; i<=5; i++) for (j=1; jReSize(10,20); for (i = 1; i <= 10; i++) for (j = 1; j <= 20; j++) (*MX)(i,j) = 100 * i + j; ColumnVector* CV = new ColumnVector(10); if (!CV) Throw(Bad_alloc("New fails ")); *CV << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10; RowVector* RV = new RowVector(CV->t() | (*CV + 10).t()); if (!RV) Throw(Bad_alloc("New fails ")); CV1 = ColumnVector(10); CV1 = 1; RV1 = RowVector(20); RV1 = 1; *MX -= 100 * *CV * RV1 + CV1 * *RV; Print(*MX); delete MX; delete CV; delete RV; } // test copying of vectors and matrices with no elements { ColumnVector dims(16); Matrix M1; Matrix M2 = M1; Print(M2); dims(1) = M2.Nrows(); dims(2) = M2.Ncols(); dims(3) = (Real)(unsigned long)M2.Store(); dims(4) = M2.Storage(); M2 = M1; dims(5) = M2.Nrows(); dims(6) = M2.Ncols(); dims(7) = (Real)(unsigned long)M2.Store(); dims(8) = M2.Storage(); M2.ReSize(10,20); M2.CleanUp(); dims(9) = M2.Nrows(); dims(10) = M2.Ncols(); dims(11) = (Real)(unsigned long)M2.Store(); dims(12) = M2.Storage(); M2.ReSize(20,10); M2.ReSize(0,0); dims(13) = M2.Nrows(); dims(14) = M2.Ncols(); dims(15) = (Real)(unsigned long)M2.Store(); dims(16) = M2.Storage(); Print(dims); } { ColumnVector dims(16); ColumnVector M1; ColumnVector M2 = M1; Print(M2); dims(1) = M2.Nrows(); dims(2) = M2.Ncols()-1; dims(3) = (Real)(unsigned long)M2.Store(); dims(4) = M2.Storage(); M2 = M1; dims(5) = M2.Nrows(); dims(6) = M2.Ncols()-1; dims(7) = (Real)(unsigned long)M2.Store(); dims(8) = M2.Storage(); M2.ReSize(10); M2.CleanUp(); dims(9) = M2.Nrows(); dims(10) = M2.Ncols()-1; dims(11) = (Real)(unsigned long)M2.Store(); dims(12) = M2.Storage(); M2.ReSize(10); M2.ReSize(0); dims(13) = M2.Nrows(); dims(14) = M2.Ncols()-1; dims(15) = (Real)(unsigned long)M2.Store(); dims(16) = M2.Storage(); Print(dims); } { ColumnVector dims(16); RowVector M1; RowVector M2 = M1; Print(M2); dims(1) = M2.Nrows()-1; dims(2) = M2.Ncols(); dims(3) = (Real)(unsigned long)M2.Store(); dims(4) = M2.Storage(); M2 = M1; dims(5) = M2.Nrows()-1; dims(6) = M2.Ncols(); dims(7) = (Real)(unsigned long)M2.Store(); dims(8) = M2.Storage(); M2.ReSize(10); M2.CleanUp(); dims(9) = M2.Nrows()-1; dims(10) = M2.Ncols(); dims(11) = (Real)(unsigned long)M2.Store(); dims(12) = M2.Storage(); M2.ReSize(10); M2.ReSize(0); dims(13) = M2.Nrows()-1; dims(14) = M2.Ncols(); dims(15) = (Real)(unsigned long)M2.Store(); dims(16) = M2.Storage(); Print(dims); } // test identity matrix { Matrix M; IdentityMatrix I(10); DiagonalMatrix D(10); D = 1; M = I; M -= D; Print(M); D -= I; Print(D); ColumnVector X(8); D = 1; X(1) = Sum(D) - Sum(I); X(2) = SumAbsoluteValue(D) - SumAbsoluteValue(I); X(3) = SumSquare(D) - SumSquare(I); X(4) = Trace(D) - Trace(I); X(5) = Maximum(D) - Maximum(I); X(6) = Minimum(D) - Minimum(I); X(7) = LogDeterminant(D).LogValue() - LogDeterminant(I).LogValue(); X(8) = LogDeterminant(D).Sign() - LogDeterminant(I).Sign(); Clean(X,0.00000001); Print(X); for (i = 1; i <= 10; i++) for (j = 1; j <= 10; j++) M(i,j) = 100 * i + j; Matrix N; N = M * I - M; Print(N); N = I * M - M; Print(N); N = M * I.i() - M; Print(N); N = I.i() * M - M; Print(N); N = I.i(); N -= I; Print(N); N = I.t(); N -= I; Print(N); N = I.t(); N += (-I); Print(N); // <---------------- D = I; N = D; D = 1; N -= D; Print(N); N = I; D = 1; N -= D; Print(N); N = M + 2 * IdentityMatrix(10); N -= (M + 2 * D); Print(N); I *= 4; D = 4; X.ReSize(14); X(1) = Sum(D) - Sum(I); X(2) = SumAbsoluteValue(D) - SumAbsoluteValue(I); X(3) = SumSquare(D) - SumSquare(I); X(4) = Trace(D) - Trace(I); X(5) = Maximum(D) - Maximum(I); X(6) = Minimum(D) - Minimum(I); X(7) = LogDeterminant(D).LogValue() - LogDeterminant(I).LogValue(); // <-- X(8) = LogDeterminant(D).Sign() - LogDeterminant(I).Sign(); int i,j; X(9) = I.Maximum1(i) - 4; X(10) = i-1; X(11) = I.Maximum2(i,j) - 4; X(12) = i-10; X(13) = j-10; X(14) = I.Nrows() - 10; Clean(X,0.00000001); Print(X); N = D.i(); N += I / (-16); Print(N); N = M * I - 4 * M; Print(N); N = I * M - 4 * M; Print(N); N = M * I.i() - 0.25 * M; Print(N); N = I.i() * M - 0.25 * M; Print(N); N = I.i(); N -= I * 0.0625; Print(N); N = I.i(); N = N - 0.0625 * I; Print(N); N = I.t(); N -= I; Print(N); D = I * 2; N = D; D = 1; N -= 8 * D; Print(N); N = I * 2; N -= 8 * D; Print(N); N = 0.5 * I + M; N -= M; N -= 2.0 * D; Print(N); IdentityMatrix J(10); J = 8; D = 4; DiagonalMatrix E(10); E = 8; N = (I + J) - (D + E); Print(N); N = (5*I + 3*J) - (5*D + 3*E); Print(N); N = (-I + J) - (-D + E); Print(N); N = (I - J) - (D - E); Print(N); N = (I | J) - (D | E); Print(N); N = (I & J) - (D & E); Print(N); N = SP(I,J) - SP(D,E); Print(N); N = D.SubMatrix(2,5,3,8) - I.SubMatrix(2,5,3,8); Print(N); N = M; N.Inject(I); D << M; N -= (M + I); N += D; Print(N); D = 4; IdentityMatrix K = I.i()*7 - J.t()/4; N = D.i() * 7 - E / 4 - K; Print(N); K = I * J; N = K - D * E; Print(N); N = I * J; N -= D * E; Print(N); K = 5*I - 3*J; N = K - (5*D - 3*E); Print(N); K = I.i(); N = K - 0.0625 * I; Print(N); K = I.t(); N = K - I; Print(N); K.ReSize(20); D.ReSize(20); D = 1; D -= K; Print(D); I.ReSize(3); J.ReSize(3); K = I * J; N = K - I; Print(N); K << D; N = K - D; Print(N); } // cout << "\nEnd of second test\n"; } newmat-1.10.4/tmt3.cpp0000644001161000116100000001172407205447544012707 0ustar rzrrzr //#define WANT_STREAM #include "include.h" #include "newmat.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif /**************************** test program ******************************/ void trymat3() { Tracer et("Third test of Matrix package"); Tracer::PrintTrace(); { Tracer et1("Stage 1"); int i,j; SymmetricMatrix S(7); for (i=1;i<=7;i++) for (j=1;j<=i;j++) S(i,j)=i*i+j; S=-S+2.0; DiagonalMatrix D(7); for (i=1;i<=7;i++) D(i,i)=S(i,i); Matrix M4(7,7); { M4=D+(D+4.0); M4=M4-D*2.0; M4=M4-4.0; Print(M4); } SymmetricMatrix S2=D; Matrix M2=S2; { M2=-D+M2; Print(M2); } UpperTriangularMatrix U2=D; { M2=U2; M2=D-M2; Print(M2); } LowerTriangularMatrix L2=D; { M2=L2; M2=D-M2; Print(M2); } M2=D; M2=M2-D; Print(M2); for (i=1;i<=7;i++) for (j=1;j<=i;j++) L2(i,j)=2.0-i*i-j; U2=L2.t(); D=D.t(); S=S.t(); M4=(L2-1.0)+(U2+1.0)-D-S; Print(M4); M4=(-L2+1.0)+(-U2-1.0)+D+S; Print(M4); } { Tracer et1("Stage 2"); int i,j; DiagonalMatrix D(6); for (i=1;i<=6;i++) D(i,i)=i*3.0+i*i+2.0; UpperTriangularMatrix U2(7); LowerTriangularMatrix L2(7); for (i=1;i<=7;i++) for (j=1;j<=i;j++) L2(i,j)=2.0-i*i+j; { U2=L2.t(); } DiagonalMatrix D1(7); for (i=1;i<=7;i++) D1(i,i)=(i-2)*(i-4); Matrix M2(6,7); for (i=1;i<=6;i++) for (j=1;j<=7;j++) M2(i,j)=2.0+i*j+i*i+2.0*j*j; Matrix MD=D; SymmetricMatrix MD1(1); MD1=D1; Matrix MX=MD*M2*MD1 - D*(M2*D1); Print(MX); MX=MD*M2*MD1 - (D*M2)*D1; Print(MX); { D.ReSize(7); for (i=1;i<=7;i++) D(i,i)=i*3.0+i*i+2.0; LowerTriangularMatrix LD(1); LD=D; UpperTriangularMatrix UD(1); UD=D; M2=U2; M2=LD*M2*MD1 - D*(U2*D1); Print(M2); M2=U2; M2=UD*M2*MD1 - (D*U2)*D1; Print(M2); M2=L2; M2=LD*M2*MD1 - D*(L2*D1); Print(M2); M2=L2; M2=UD*M2*MD1 - (D*L2)*D1; Print(M2); } } { Tracer et1("Stage 3"); // test inverse * scalar DiagonalMatrix D(6); for (int i=1;i<=6;i++) D(i)=i*i; DiagonalMatrix E = D.i() * 4.0; DiagonalMatrix I(6); I = 1.0; E=D*E-I*4.0; Print(E); E = D.i() / 0.25; E=D*E-I*4.0; Print(E); } { Tracer et1("Stage 4"); Matrix sigma(3,3); Matrix sigmaI(3,3); sigma = 0; sigma(1,1) = 1.0; sigma(2,2) = 1.0; sigma(3,3) = 1.0; sigmaI = sigma.i(); sigmaI -= sigma; Clean(sigmaI, 0.000000001); Print(sigmaI); } { Tracer et1("Stage 5"); Matrix X(5,5); DiagonalMatrix DM(5); for (int i=1; i<=5; i++) for (int j=1; j<=5; j++) X(i,j) = (23*i+59*j) % 43; DM << 1 << 8 << -7 << 2 << 3; Matrix Y = X.i() * DM; Y = X * Y - DM; Clean(Y, 0.000000001); Print(Y); } { Tracer et1("Stage 6"); // test reverse function ColumnVector CV(10), RCV(10); CV << 2 << 7 << 1 << 6 << -3 << 1 << 8 << -4 << 0 << 17; RCV << 17 << 0 << -4 << 8 << 1 << -3 << 6 << 1 << 7 << 2; ColumnVector X = CV - RCV.Reverse(); Print(X); RowVector Y = CV.t() - RCV.t().Reverse(); Print(Y); DiagonalMatrix D = CV.AsDiagonal() - RCV.AsDiagonal().Reverse(); Print(D); X = CV & CV.Rows(1,9).Reverse(); ColumnVector Z(19); Z.Rows(1,10) = RCV.Reverse(); Z.Rows(11,19) = RCV.Rows(2,10); X -= Z; Print(X); Z -= Z.Reverse(); Print(Z); Matrix A(3,3); A << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9; Matrix B(3,3); B << 9 << 8 << 7 << 6 << 5 << 4 << 3 << 2 << 1; Matrix Diff = A - B.Reverse(); Print(Diff); Diff = (-A).Reverse() + B; Print(Diff); UpperTriangularMatrix U; U << A.Reverse(); Diff = U; U << B; Diff -= U; Print(Diff); U << (-A).Reverse(); Diff = U; U << B; Diff += U; Print(Diff); } { Tracer et1("Stage 7"); // test IsSingular function ColumnVector XX(4); Matrix A(3,3); A = 0; CroutMatrix B1 = A; XX(1) = B1.IsSingular() ? 0 : 1; A << 1 << 3 << 6 << 7 << 11 << 13 << 2 << 4 << 1; CroutMatrix B2(A); XX(2) = B2.IsSingular() ? 1 : 0; BandMatrix C(3,1,1); C.Inject(A); BandLUMatrix B3(C); XX(3) = B3.IsSingular() ? 1 : 0; C = 0; BandLUMatrix B4(C); XX(4) = B4.IsSingular() ? 0 : 1; Print(XX); } { Tracer et1("Stage 8"); // inverse with vector of 0s Matrix A(3,3); Matrix Z(3,3); ColumnVector X(6); A << 1 << 3 << 6 << 7 << 11 << 13 << 2 << 4 << 1; Z = 0; Matrix B = (A | Z) & (Z | A); // 6 * 6 matrix X = 0.0; X = B.i() * X; Print(X); // also check inverse with non-zero Y Matrix Y(3,3); Y << 0.0 << 1.0 << 1.0 << 5.0 << 0.0 << 5.0 << 3.0 << 3.0 << 0.0; Matrix YY = Y & Y; // stack Y matrices YY = B.i() * YY; Matrix Y1 = A.i() * Y; YY -= Y1 & Y1; Clean(YY, 0.000000001); Print(YY); Y1 = A * Y1 - Y; Clean(Y1, 0.000000001); Print(Y1); } } newmat-1.10.4/tmt4.cpp0000644001161000116100000001104107365115542012675 0ustar rzrrzr //#define WANT_STREAM #include "include.h" #include "newmat.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif /**************************** test program ******************************/ void trymat4() { // cout << "\nFourth test of Matrix package\n"; Tracer et("Fourth test of Matrix package"); Tracer::PrintTrace(); int i,j; { Tracer et1("Stage 1"); Matrix M(10,10); UpperTriangularMatrix U(10); for (i=1;i<=10;i++) for (j=1;j<=10;j++) M(i,j) = 100*i+j; U << -M; Matrix X1 = M.Rows(2,4); Matrix Y1 = U.t().Rows(2,4); Matrix X = U; { Print(Matrix(X.Columns(2,4).t()-Y1)); } RowVector RV = M.Row(5); { X.ReSize(3,10); X.Row(1) << M.Row(2); X.Row(2) << M.Row(3); X.Row(3) << M.Row(4); Print(Matrix(X-X1)); } { UpperTriangularMatrix V = U.SymSubMatrix(3,5); Matrix MV = U.SubMatrix(3,5,3,5); { Print(Matrix(MV-V)); } Matrix X2 = M.t().Columns(2,4); { Print(Matrix(X2-X1.t())); } Matrix Y2 = U.Columns(2,4); { Print(Matrix(Y2-Y1.t())); } ColumnVector CV = M.t().Column(5); { Print(ColumnVector(CV-RV.t())); } X.ReSize(10,3); M = M.t(); X.Column(1) << M.Column(2); X.Column(2) << M.Column(3); X.Column(3) << M.Column(4); Print(Matrix(X-X2)); } } { Tracer et1("Stage 2"); Matrix M; Matrix X; M.ReSize(5,8); for (i=1;i<=5;i++) for (j=1;j<=8;j++) M(i,j) = 100*i+j; { X = M.Columns(5,8); M.Columns(5,8) << M.Columns(1,4); M.Columns(1,4) << X; X = M.Columns(3,4); M.Columns(3,4) << M.Columns(1,2); M.Columns(1,2) << X; X = M.Columns(7,8); M.Columns(7,8) << M.Columns(5,6); M.Columns(5,6) << X; } { X = M.Column(2); M.Column(2) = M.Column(1); M.Column(1) = X; X = M.Column(4); M.Column(4) = M.Column(3); M.Column(3) = X; X = M.Column(6); M.Column(6) = M.Column(5); M.Column(5) = X; X = M.Column(8); M.Column(8) = M.Column(7); M.Column(7) = X; X.ReSize(5,8); } for (i=1;i<=5;i++) for (j=1;j<=8;j++) X(i,9-j) = 100*i+j; Print(Matrix(X-M)); } { Tracer et1("Stage 3"); // try submatrices of zero dimension Matrix A(4,5); Matrix B, C; for (i=1; i<=4; i++) for (j=1; j<=5; j++) A(i,j) = 100+i*10+j; B = A + 100; C = A | B.Columns(4,3); Print(Matrix(A - C)); C = A | B.Columns(1,0); Print(Matrix(A - C)); C = A | B.Columns(6,5); Print(Matrix(A - C)); C = A & B.Rows(2,1); Print(Matrix(A - C)); } { Tracer et1("Stage 4"); BandMatrix BM(5,3,2); BM(1,1) = 1; BM(1,2) = 2; BM(1,3) = 3; BM(2,1) = 4; BM(2,2) = 5; BM(2,3) = 6; BM(2,4) = 7; BM(3,1) = 8; BM(3,2) = 9; BM(3,3) =10; BM(3,4) =11; BM(3,5) =12; BM(4,1) =13; BM(4,2) =14; BM(4,3) =15; BM(4,4) =16; BM(4,5) =17; BM(5,2) =18; BM(5,3) =19; BM(5,4) =20; BM(5,5) =21; SymmetricBandMatrix SM(5,3); SM.Inject(BandMatrix(BM + BM.t())); Matrix A = BM + 1; Matrix M = A + A.t() - 2; Matrix C = A.i() * BM; C = A * C - BM; Clean(C, 0.000000001); Print(C); C = A.i() * SM; C = A * C - M; Clean(C, 0.000000001); Print(C); // check row-wise load BandMatrix BM1(5,3,2); BM1.Row(1) << 1 << 2 << 3; BM1.Row(2) << 4 << 5 << 6 << 7; BM1.Row(3) << 8 << 9 << 10 << 11 << 12; BM1.Row(4) << 13 << 14 << 15 << 16 << 17; BM1.Row(5) << 18 << 19 << 20 << 21; Matrix M1 = BM1 - BM; Print(M1); } { Tracer et1("Stage 5"); Matrix X(4,4); X << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 <<10 <<11 <<12 <<13 <<14 <<15 <<16; Matrix Y(4,0); Y = X | Y; X -= Y; Print(X); DiagonalMatrix D(1); D << 23; // matrix input with just one value D(1) -= 23; Print(D); } { Tracer et1("Stage 6"); Matrix h (2,2); h << 1.0 << 2.0 << 0.0 << 1.0 ; RowVector c(2); c << 0.0 << 1.0; h -= c & c; h -= c.t().Reverse() | c.Reverse().t(); Print(h); } { Tracer et1("Stage 7"); // Check row-wise input for diagonal matrix DiagonalMatrix D(4); D << 18 << 23 << 31 << 17; DiagonalMatrix D1(4); D1.Row(1) << 18; D1.Row(2) << 23; D1.Row(3) << 31; D1.Row(4) << 17; D1 -= D; Print(D1); D1(1) = 18; D1(2) = 23; D1(3) = 31; D1(4) = 17; D1 -= D; Print(D1); } // cout << "\nEnd of fourth test\n"; } newmat-1.10.4/tmt5.cpp0000644001161000116100000000655607342573370012717 0ustar rzrrzr //#define WANT_STREAM #include "include.h" #include "newmat.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif // **************************** test program ****************************** ReturnMatrix Returner0(const GenericMatrix& GM) { Matrix M = GM; M.Release(); return M; } ReturnMatrix Returner1(const GenericMatrix& GM) { Matrix M = GM+1; M.Release(); return M; } ReturnMatrix Returner2(const GenericMatrix& GM) { UpperBandMatrix M = GM*2; M.Release(); return M; } ReturnMatrix Returner3(const GenericMatrix& GM) { LowerBandMatrix M = GM*3; M.Release(); return M; } ReturnMatrix Returner4(const GenericMatrix& GM) { SymmetricMatrix M = GM+4; M.Release(); return M; } ReturnMatrix Returner5(const GenericMatrix& GM) { SymmetricBandMatrix M = GM*5; M.Release(); return M; } ReturnMatrix Returner6(const GenericMatrix& GM) { BandMatrix M = GM*6; M.Release(); return M; } ReturnMatrix Returner7(const GenericMatrix& GM) { DiagonalMatrix M = GM*7; M.Release(); return M; } void trymat5() { // cout << "\nFifth test of Matrix package\n"; Tracer et("Fifth test of Matrix package"); Tracer::PrintTrace(); int i,j; Matrix A(5,6); for (i=1;i<=5;i++) for (j=1;j<=6;j++) A(i,j)=1+i*j+i*i+j*j; ColumnVector CV(6); for (i=1;i<=6;i++) CV(i)=i*i+3; ColumnVector CV2(5); for (i=1;i<=5;i++) CV2(i)=1.0; ColumnVector CV1=CV; { CV=A*CV; RowVector RV=CV.t(); // RowVector RV; RV=CV.t(); RV=RV-1.0; CV=(RV*A).t()+A.t()*CV2; CV1=(A.t()*A)*CV1 - CV; Print(CV1); } CV1.ReSize(6); CV2.ReSize(6); CV.ReSize(6); for (i=1;i<=6;i++) { CV1(i)=i*3+1; CV2(i)=10-i; CV(i)=11+i*2; } ColumnVector CX=CV2-CV; { CX=CX+CV1; Print(CX); } Print(ColumnVector(CV1+CV2-CV)); RowVector RV=CV.t(); RowVector RV1=CV1.t(); RowVector R=RV-RV1; Print(RowVector(R-CV2.t())); // test loading of list RV.ReSize(10); for (i=1;i<=10;i++) RV(i) = i*i; RV1.ReSize(10); RV1 << 1 << 4 << 9 << 16 << 25 << 36 << 49 << 64 << 81 << 100; // << 121; Print(RowVector(RV-RV1)); et.ReName("Fifth test of Matrix package - almost at end"); Matrix X(2,3); X << 11 << 12 << 13 << 21 << 22 << 23; Matrix Y = X.t(); // check simple transpose X(1,1) -= 11; X(1,2) -= 12; X(1,3) -= 13; X(2,1) -= 21; X(2,2) -= 22; X(2,3) -= 23; Print(X); Y(1,1) -= 11; Y(2,1) -= 12; Y(3,1) -= 13; Y(1,2) -= 21; Y(2,2) -= 22; Y(3,2) -= 23; Print(Y); et.ReName("Fifth test of Matrix package - at end"); RV = Returner1(RV)-1; Print(RowVector(RV-RV1)); CV1 = Returner1(RV.t())-1; Print(ColumnVector(RV.t()-CV1)); #ifndef DONT_DO_NRIC nricMatrix AA = A; X = Returner1(AA)-A-1; Print(X); #endif UpperTriangularMatrix UT(31); for (i=1; i<=31; i++) for (j=i; j<=31; j++) UT(i,j) = i+j+(i-j)*(i-2*j); UpperBandMatrix UB(31,5); UB.Inject(UT); LowerTriangularMatrix LT = UT.t(); LowerBandMatrix LB(31,5); LB.Inject(LT); A = Returner0(UB)-LB.t(); Print(A); A = Returner2(UB).t()-LB*2; Print(A); A = Returner3(LB).t()-UB*3; Print(A); SymmetricMatrix SM; SM << (UT+LT); A = Returner4(SM)-UT-LT-4; Print(A); SymmetricBandMatrix SB(31,5); SB.Inject(SM); A = Returner5(SB)/5-UB-LB; Print(A); BandMatrix B = UB+LB*LB; A = LB; A = Returner6(B)/6 - UB - A*A; Print(A); DiagonalMatrix D; D << UT; D << (Returner7(D)/7 - UT); Print(D); // cout << "\nEnd of fifth test\n"; } newmat-1.10.4/tmt6.cpp0000644001161000116100000001101207423523702012671 0ustar rzrrzr //#define WANT_STREAM #define WANT_MATH #include "include.h" #include "newmatap.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif /**************************** test program ******************************/ // slow sort program static void SimpleSortDescending(Real* first, const int length) { int i = length; while (--i) { Real x = *first; Real* f = first; Real* g = f; int j = i; while (j--) if (x < *(++f)) { g = f; x = *g; } *g = *first; *first++ = x; } } static void TestSort(int n) { // make some data RowVector X(n); int i; for (i = 1; i <= n; i++) X(i) = sin((Real)i) + 0.3 * cos(i/5.0) - 0.6 * sin(i/7.0) + 0.2 * sin(2.0 * i); RowVector X_Sorted = X; SimpleSortDescending(X_Sorted.Store(), n); RowVector A = X + X.Reverse(); SimpleSortDescending(A.Store(), n); // test descending sort RowVector Y = X; SortDescending(Y); Y -= X_Sorted; Print(Y); Y = X_Sorted; SortDescending(Y); Y -= X_Sorted; Print(Y); Y = X_Sorted.Reverse(); SortDescending(Y); Y -= X_Sorted; Print(Y); Y = X + X.Reverse(); SortDescending(Y); Y -= A; Print(Y); // test ascending sort Y = X; SortAscending(Y); Y -= X_Sorted.Reverse(); Print(Y); Y = X_Sorted; SortAscending(Y); Y -= X_Sorted.Reverse(); Print(Y); Y = X_Sorted.Reverse(); SortAscending(Y); Y -= X_Sorted.Reverse(); Print(Y); Y = X + X.Reverse(); SortAscending(Y); Y -= A.Reverse(); Print(Y); } void trymat6() { Tracer et("Sixth test of Matrix package"); Tracer::PrintTrace(); int i,j; DiagonalMatrix D(6); UpperTriangularMatrix U(6); for (i=1;i<=6;i++) { for (j=i;j<=6;j++) U(i,j)=i*i*i-50; D(i,i)=i*i+i-10; } LowerTriangularMatrix L=(U*3.0).t(); SymmetricMatrix S(6); for (i=1;i<=6;i++) for (j=i;j<=6;j++) S(i,j)=i*i+2.0+j; Matrix MD=D; Matrix ML=L; Matrix MU=U; Matrix MS=S; Matrix M(6,6); for (i=1;i<=6;i++) for (j=1;j<=6;j++) M(i,j)=i*j+i*i-10.0; { Tracer et1("Stage 1"); Print(Matrix(MS+(-MS))); Print(Matrix((S+M)-(MS+M))); Print(Matrix((M+U)-(M+MU))); Print(Matrix((M+L)-(M+ML))); } { Tracer et1("Stage 2"); Print(Matrix((M+D)-(M+MD))); Print(Matrix((U+D)-(MU+MD))); Print(Matrix((D+L)-(ML+MD))); Print(Matrix((-U+D)+MU-MD)); Print(Matrix((-L+D)+ML-MD)); } { Tracer et1("Stage 3 - concatenate"); RowVector A(5); A << 1 << 2 << 3 << 4 << 5; RowVector B(5); B << 3 << 1 << 4 << 1 << 5; Matrix C(3,5); C << 2 << 3 << 5 << 7 << 11 << 13 << 17 << 19 << 23 << 29 << 31 << 37 << 41 << 43 << 47; Matrix X1 = A & B & C; Matrix X2 = (A.t() | B.t() | C.t()).t(); Matrix X3(5,5); X3.Row(1)=A; X3.Row(2)=B; X3.Rows(3,5)=C; Print(Matrix(X1-X2)); Print(Matrix(X1-X3)); LowerTriangularMatrix LT1; LT1 << (A & B & C); UpperTriangularMatrix UT1; UT1 << (A.t() | B.t() | C.t()); Print(LowerTriangularMatrix(LT1-UT1.t())); DiagonalMatrix D1; D1 << (A.t() | B.t() | C.t()); ColumnVector At = A.t(); ColumnVector Bt = B.t(); Matrix Ct = C.t(); LowerTriangularMatrix LT2; LT2 << (At | Bt | Ct); UpperTriangularMatrix UT2; UT2 << (At.t() & Bt.t() & Ct.t()); Matrix ABt = At | Bt; DiagonalMatrix D2; D2 << (ABt | Ct); Print(LowerTriangularMatrix(LT2-UT2.t())); Print(DiagonalMatrix(D1-D2)); Print(Matrix(LT1+UT2-D2-X1)); Matrix M1 = LT1 | UT2; Matrix M2 = UT1 & LT2; Print(Matrix(M1-M2.t())); M1 = UT2 | LT1; M2 = LT2 & UT1; Print(Matrix(M1-M2.t())); M1 = (LT1 | UT2) & (UT2 | LT1); M2 = (UT1 & LT2) | (LT2 & UT1); Print(Matrix(M1-M2.t())); SymmetricMatrix SM1; SM1 << (M1 + M1.t()); SymmetricMatrix SM2; SM2 << ((SM1 | M1) & (M1.t() | SM1)); Matrix M3(20,20); M3.SubMatrix(1,10,1,10) = SM1; M3.SubMatrix(1,10,11,20) = M1; M3.SubMatrix(11,20,1,10) = M2; M3.SubMatrix(11,20,11,20) = SM1; Print(Matrix(M3-SM2)); SymmetricMatrix SM(15); SM = 0; SM.SymSubMatrix(1,10) = SM1; M3.ReSize(15,15); M3 = 0; M3.SubMatrix(1,10,1,10) = SM1; M3 -= SM; Print(M3); SM = 0; SM.SymSubMatrix(6,15) = SM1; M3.ReSize(15,15); M3 = 0; M3.SubMatrix(6,15,6,15) = SM1; M3 = M3.t() - SM; Print(M3); } { Tracer et1("Stage 4 - sort"); TestSort(1); TestSort(2); TestSort(3); TestSort(4); TestSort(15); TestSort(16); TestSort(17); TestSort(18); TestSort(99); TestSort(100); TestSort(101); } // cout << "\nEnd of sixth test\n"; } newmat-1.10.4/tmt7.cpp0000644001161000116100000001014707205447414012705 0ustar rzrrzr //#define WANT_STREAM #include "include.h" #include "newmat.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif /**************************** test program ******************************/ void trymat7() { // cout << "\nSeventh test of Matrix package\n"; Tracer et("Seventh test of Matrix package"); Tracer::PrintTrace(); int i,j; DiagonalMatrix D(6); UpperTriangularMatrix U(6); for (i=1;i<=6;i++) { for (j=i;j<=6;j++) U(i,j)=i*i*j-50; D(i,i)=i*i+i-10; } LowerTriangularMatrix L=(U*3.0).t(); SymmetricMatrix S(6); for (i=1;i<=6;i++) for (j=i;j<=6;j++) S(i,j)=i*i+2.0+j; Matrix MD=D; Matrix ML=L; Matrix MU=U; Matrix MS=S; Matrix M(6,6); for (i=1;i<=6;i++) for (j=1;j<=6;j++) M(i,j)=i*j+i*i-10.0; { Tracer et1("Stage 1"); Print(Matrix((S-M)-(MS-M))); Print(Matrix((-M-S)+(MS+M))); Print(Matrix((U-M)-(MU-M))); } { Tracer et1("Stage 2"); Print(Matrix((L-M)+(M-ML))); Print(Matrix((D-M)+(M-MD))); Print(Matrix((D-S)+(MS-MD))); Print(Matrix((D-L)+(ML-MD))); } { M=MU.t(); } LowerTriangularMatrix LY=D.i()*U.t(); { Tracer et1("Stage 3"); MS=D*LY-M; Clean(MS,0.00000001); Print(MS); L=U.t(); LY=D.i()*L; MS=D*LY-M; Clean(MS,0.00000001); Print(MS); } { Tracer et1("Stage 4"); UpperTriangularMatrix UT(11); int i, j; for (i=1;i<=11;i++) for (j=i;j<=11;j++) UT(i,j)=i*i+j*3; GenericMatrix GM; Matrix X; UpperBandMatrix UB(11,3); UB.Inject(UT); UT = UB; UpperBandMatrix UB2 = UB / 8; GM = UB2-UT/8; X = GM; Print(X); SymmetricBandMatrix SB(11,4); SB << (UB + UB.t()); X = SB - UT - UT.t(); Print(X); BandMatrix B = UB + UB.t()*2; DiagonalMatrix D; D << B; X.ReSize(1,1); X(1,1) = Trace(B)-Sum(D); Print(X); X = SB + 5; Matrix X1=X; X = SP(UB,X); Matrix X2 =UB; X1 = (X1.AsDiagonal() * X2.AsDiagonal()).AsRow()-X.AsColumn().t(); Print(X1); X1=SB.t(); X2 = B.t(); X = SB.i() * B - X1.i() * X2.t(); Clean(X,0.00000001); Print(X); X = SB.i(); X = X * B - X1.i() * X2.t(); Clean(X,0.00000001); Print(X); D = 1; X = SB.i() * SB - D; Clean(X,0.00000001); Print(X); ColumnVector CV(11); CV << 2 << 6 <<3 << 8 << -4 << 17.5 << 2 << 1 << -2 << 5 << 3.75; D << 2 << 6 <<3 << 8 << -4 << 17.5 << 2 << 1 << -2 << 5 << 3.75; X = CV.AsDiagonal(); X = X-D; Print(X); SymmetricBandMatrix SB1(11,7); SB1 = 5; SymmetricBandMatrix SB2 = SB1 + D; X.ReSize(11,11); X=0; for (i=1;i<=11;i++) for (j=1;j<=11;j++) { if (abs(i-j)<=7) X(i,j)=5; if (i==j) X(i,j)+=CV(i); } SymmetricMatrix SM; SM.ReSize(11); SM=SB; SB = SB+SB2; X1 = SM+X-SB; Print(X1); SB2=0; X2=SB2; X1=SB; Print(X2); for (i=1;i<=11;i++) SB2.Column(i)<a3) ? i : a3; j<=a4; j++) M3(i-a1+1,j-a3+1) = 100*i + j; Print(Matrix(M2-M3)); } { Tracer et1("Stage 8"); a1=3; a2=9; a3=2; a4=7; U.ReSize(10); for (i=1; i<=10; i++) for (j=i; j<=10; j++) U(i,j) = 100*i + j; M2 = U.SubMatrix(a1,a2,a3,a4); M3.ReSize(a2-a1+1,a4-a3+1); M3=0.0; for (i=a1; i<=a2; i++) for (j=(i>a3) ? i : a3; j<=a4; j++) M3(i-a1+1,j-a3+1) = 100*i + j; Print(Matrix(M2-M3)); } { Tracer et1("Stage 9"); a1=4; a2=6; a3=2; a4=5; U.ReSize(10); for (i=1; i<=10; i++) for (j=i; j<=10; j++) U(i,j) = 100*i + j; M2 = U.SubMatrix(a1,a2,a3,a4); M3.ReSize(a2-a1+1,a4-a3+1); M3=0.0; for (i=a1; i<=a2; i++) for (j=(i>a3) ? i : a3; j<=a4; j++) M3(i-a1+1,j-a3+1) = 100*i + j; Print(Matrix(M2-M3)); } { Tracer et1("Stage 10"); TestClass TC; Matrix M = TC.Sum() - 9; Print(M); } // cout << "\nEnd of eleventh test\n"; } newmat-1.10.4/tmtc.cpp0000644001161000116100000001232607647677452013003 0ustar rzrrzr //#define WANT_STREAM #include "include.h" #include "newmat.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif void trymatc() { // cout << "\nTwelfth test of Matrix package\n"; Tracer et("Twelfth test of Matrix package"); Tracer::PrintTrace(); DiagonalMatrix D(15); D=1.5; Matrix A(15,15); int i,j; for (i=1;i<=15;i++) for (j=1;j<=15;j++) A(i,j)=i*i+j-150; { A = A + D; } ColumnVector B(15); for (i=1;i<=15;i++) B(i)=i+i*i-150.0; { Tracer et1("Stage 1"); ColumnVector B1=B; B=(A*2.0).i() * B1; Matrix X = A*B-B1/2.0; Clean(X, 0.000000001); Print(X); A.ReSize(3,5); for (i=1; i<=3; i++) for (j=1; j<=5; j++) A(i,j) = i+100*j; B = A.AsColumn()+10000; RowVector R = (A+10000).AsColumn().t(); Print( RowVector(R-B.t()) ); } { Tracer et1("Stage 2"); B = A.AsColumn()+10000; Matrix XR = (A+10000).AsMatrix(15,1).t(); Print( RowVector(XR-B.t()) ); } { Tracer et1("Stage 3"); B = (A.AsMatrix(15,1)+A.AsColumn())/2.0+10000; Matrix MR = (A+10000).AsColumn().t(); Print( RowVector(MR-B.t()) ); B = (A.AsMatrix(15,1)+A.AsColumn())/2.0; MR = A.AsColumn().t(); Print( RowVector(MR-B.t()) ); } { Tracer et1("Stage 4"); B = (A.AsMatrix(15,1)+A.AsColumn())/2.0; RowVector R = A.AsColumn().t(); Print( RowVector(R-B.t()) ); } { Tracer et1("Stage 5"); RowVector R = (A.AsColumn()-5000).t(); B = ((R.t()+10000) - A.AsColumn())-5000; Print( RowVector(B.t()) ); } { Tracer et1("Stage 6"); B = A.AsColumn(); ColumnVector B1 = (A+10000).AsColumn() - 10000; Print(ColumnVector(B1-B)); } { Tracer et1("Stage 7"); Matrix X = B.AsMatrix(3,5); Print(Matrix(X-A)); for (i=1; i<=3; i++) for (j=1; j<=5; j++) B(5*(i-1)+j) -= i+100*j; Print(B); } { Tracer et1("Stage 8"); A.ReSize(7,7); D.ReSize(7); for (i=1; i<=7; i++) for (j=1; j<=7; j++) A(i,j) = i*j*j; for (i=1; i<=7; i++) D(i,i) = i; UpperTriangularMatrix U; U << A; Matrix X = A; for (i=1; i<=7; i++) X(i,i) = i; A.Inject(D); Print(Matrix(X-A)); X = U; U.Inject(D); A = U; for (i=1; i<=7; i++) X(i,i) = i; Print(Matrix(X-A)); } { Tracer et1("Stage 9"); A.ReSize(7,5); for (i=1; i<=7; i++) for (j=1; j<=5; j++) A(i,j) = i+100*j; Matrix Y = A; Y = Y - ((const Matrix&)A); Print(Y); Matrix X = A; // X.Release(); Y = A; Y = ((const Matrix&)X) - A; Print(Y); Y = 0.0; Y = ((const Matrix&)X) - ((const Matrix&)A); Print(Y); } { Tracer et1("Stage 10"); // some tests on submatrices UpperTriangularMatrix U(20); for (i=1; i<=20; i++) for (j=i; j<=20; j++) U(i,j)=100 * i + j; UpperTriangularMatrix V = U.SymSubMatrix(1,5); UpperTriangularMatrix U1 = U; U1.SubMatrix(4,8,5,9) /= 2; U1.SubMatrix(4,8,5,9) += 388 * V; U1.SubMatrix(4,8,5,9) *= 2; U1.SubMatrix(4,8,5,9) += V; U1 -= U; UpperTriangularMatrix U2 = U1; U1 << U1.SubMatrix(4,8,5,9); U2.SubMatrix(4,8,5,9) -= U1; Print(U2); U1 -= (777*V); Print(U1); U1 = U; U1.SubMatrix(4,8,5,9) -= U.SymSubMatrix(1,5); U1 -= U; U2 = U1; U1 << U1.SubMatrix(4,8,5,9); U2.SubMatrix(4,8,5,9) -= U1; Print(U2); U1 += V; Print(U1); U1 = U; U1.SubMatrix(3,10,15,19) += 29; U1 -= U; Matrix X = U1.SubMatrix(3,10,15,19); X -= 29; Print(X); U1.SubMatrix(3,10,15,19) *= 0; Print(U1); LowerTriangularMatrix L = U.t(); LowerTriangularMatrix M = L.SymSubMatrix(1,5); LowerTriangularMatrix L1 = L; L1.SubMatrix(5,9,4,8) /= 2; L1.SubMatrix(5,9,4,8) += 388 * M; L1.SubMatrix(5,9,4,8) *= 2; L1.SubMatrix(5,9,4,8) += M; L1 -= L; LowerTriangularMatrix L2 = L1; L1 << L1.SubMatrix(5,9,4,8); L2.SubMatrix(5,9,4,8) -= L1; Print(L2); L1 -= (777*M); Print(L1); L1 = L; L1.SubMatrix(5,9,4,8) -= L.SymSubMatrix(1,5); L1 -= L; L2 =L1; L1 << L1.SubMatrix(5,9,4,8); L2.SubMatrix(5,9,4,8) -= L1; Print(L2); L1 += M; Print(L1); L1 = L; L1.SubMatrix(15,19,3,10) -= 29; L1 -= L; X = L1.SubMatrix(15,19,3,10); X += 29; Print(X); L1.SubMatrix(15,19,3,10) *= 0; Print(L1); } { Tracer et1("Stage 11"); // more tests on submatrices Matrix M(20,30); for (i=1; i<=20; i++) for (j=1; j<=30; j++) M(i,j)=100 * i + j; Matrix M1 = M; for (j=1; j<=30; j++) { ColumnVector CV = 3 * M1.Column(j); M.Column(j) += CV; } for (i=1; i<=20; i++) { RowVector RV = 5 * M1.Row(i); M.Row(i) -= RV; } M += M1; Print(M); } { Tracer et1("Stage 12"); // more tests on Release Matrix M(20,30); for (i=1; i<=20; i++) for (j=1; j<=30; j++) M(i,j)=100 * i + j; Matrix M1 = M; M.Release(); Matrix M2 = M; Matrix X = M; Print(X); X = M1 - M2; Print(X); #ifndef DONT_DO_NRIC nricMatrix N = M1; nricMatrix N1 = N; N.Release(); nricMatrix N2 = N; nricMatrix Y = N; Print(Y); Y = N1 - N2; Print(Y); #endif } // cout << "\nEnd of twelfth test\n"; } newmat-1.10.4/tmtd.cpp0000644001161000116100000001335107401512242012750 0ustar rzrrzr //#define WANT_STREAM #include "include.h" #include "newmatap.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif ReturnMatrix Inverter(const CroutMatrix& X) { Matrix Y = X.i(); Y.Release(); return Y.ForReturn(); } void trymatd() { Tracer et("Thirteenth test of Matrix package"); Tracer::PrintTrace(); Matrix X(5,20); int i,j; for (j=1;j<=20;j++) X(1,j) = j+1; for (i=2;i<=5;i++) for (j=1;j<=20; j++) X(i,j) = (long)X(i-1,j) * j % 1001; SymmetricMatrix S; S << X * X.t(); Matrix SM = X * X.t() - S; Print(SM); LowerTriangularMatrix L = Cholesky(S); Matrix Diff = L*L.t()-S; Clean(Diff, 0.000000001); Print(Diff); { Tracer et1("Stage 1"); LowerTriangularMatrix L1(5); Matrix Xt = X.t(); Matrix Xt2 = Xt; QRZT(X,L1); Diff = L - L1; Clean(Diff,0.000000001); Print(Diff); UpperTriangularMatrix Ut(5); QRZ(Xt,Ut); Diff = L - Ut.t(); Clean(Diff,0.000000001); Print(Diff); Matrix Y(3,20); for (j=1;j<=20;j++) Y(1,j) = 22-j; for (i=2;i<=3;i++) for (j=1;j<=20; j++) Y(i,j) = (long)Y(i-1,j) * j % 101; Matrix Yt = Y.t(); Matrix M,Mt; Matrix Y2=Y; QRZT(X,Y,M); QRZ(Xt,Yt,Mt); Diff = Xt - X.t(); Clean(Diff,0.000000001); Print(Diff); Diff = Yt - Y.t(); Clean(Diff,0.000000001); Print(Diff); Diff = Mt - M.t(); Clean(Diff,0.000000001); Print(Diff); Diff = Y2 * Xt2 * S.i() - M * L.i(); Clean(Diff,0.000000001); Print(Diff); } ColumnVector C1(5); { Tracer et1("Stage 2"); X.ReSize(5,5); for (j=1;j<=5;j++) X(1,j) = j+1; for (i=2;i<=5;i++) for (j=1;j<=5; j++) X(i,j) = (long)X(i-1,j) * j % 1001; for (i=1;i<=5;i++) C1(i) = i*i; CroutMatrix A = X; ColumnVector C2 = A.i() * C1; C1 = X.i() * C1; X = C1 - C2; Clean(X,0.000000001); Print(X); } { Tracer et1("Stage 3"); X.ReSize(7,7); for (j=1;j<=7;j++) X(1,j) = j+1; for (i=2;i<=7;i++) for (j=1;j<=7; j++) X(i,j) = (long)X(i-1,j) * j % 1001; C1.ReSize(7); for (i=1;i<=7;i++) C1(i) = i*i; RowVector R1 = C1.t(); Diff = R1 * X.i() - ( X.t().i() * R1.t() ).t(); Clean(Diff,0.000000001); Print(Diff); } { Tracer et1("Stage 4"); X.ReSize(5,5); for (j=1;j<=5;j++) X(1,j) = j+1; for (i=2;i<=5;i++) for (j=1;j<=5; j++) X(i,j) = (long)X(i-1,j) * j % 1001; C1.ReSize(5); for (i=1;i<=5;i++) C1(i) = i*i; CroutMatrix A1 = X*X; ColumnVector C2 = A1.i() * C1; C1 = X.i() * C1; C1 = X.i() * C1; X = C1 - C2; Clean(X,0.000000001); Print(X); } { Tracer et1("Stage 5"); int n = 40; SymmetricBandMatrix B(n,2); B = 0.0; for (i=1; i<=n; i++) { B(i,i) = 6; if (i<=n-1) B(i,i+1) = -4; if (i<=n-2) B(i,i+2) = 1; } B(1,1) = 5; B(n,n) = 5; SymmetricMatrix A = B; ColumnVector X(n); X(1) = 429; for (i=2;i<=n;i++) X(i) = (long)X(i-1) * 31 % 1001; X = X / 100000L; // the matrix B is rather ill-conditioned so the difficulty is getting // good agreement (we have chosen X very small) may not be surprising; // maximum element size in B.i() is around 1400 ColumnVector Y1 = A.i() * X; LowerTriangularMatrix C1 = Cholesky(A); ColumnVector Y2 = C1.t().i() * (C1.i() * X) - Y1; Clean(Y2, 0.000000001); Print(Y2); UpperTriangularMatrix CU = C1.t().i(); LowerTriangularMatrix CL = C1.i(); Y2 = CU * (CL * X) - Y1; Clean(Y2, 0.000000001); Print(Y2); Y2 = B.i() * X - Y1; Clean(Y2, 0.000000001); Print(Y2); LowerBandMatrix C2 = Cholesky(B); Matrix M = C2 - C1; Clean(M, 0.000000001); Print(M); ColumnVector Y3 = C2.t().i() * (C2.i() * X) - Y1; Clean(Y3, 0.000000001); Print(Y3); CU = C1.t().i(); CL = C1.i(); Y3 = CU * (CL * X) - Y1; Clean(Y3, 0.000000001); Print(Y3); Y3 = B.i() * X - Y1; Clean(Y3, 0.000000001); Print(Y3); SymmetricMatrix AI = A.i(); Y2 = AI*X - Y1; Clean(Y2, 0.000000001); Print(Y2); SymmetricMatrix BI = B.i(); BandMatrix C = B; Matrix CI = C.i(); M = A.i() - CI; Clean(M, 0.000000001); Print(M); M = B.i() - CI; Clean(M, 0.000000001); Print(M); M = AI-BI; Clean(M, 0.000000001); Print(M); M = AI-CI; Clean(M, 0.000000001); Print(M); M = A; AI << M; M = AI-A; Clean(M, 0.000000001); Print(M); C = B; BI << C; M = BI-B; Clean(M, 0.000000001); Print(M); } { Tracer et1("Stage 5"); SymmetricMatrix A(4), B(4); A << 5 << 1 << 4 << 2 << 1 << 6 << 1 << 0 << 1 << 7; B << 8 << 1 << 5 << 1 << 0 << 9 << 2 << 1 << 0 << 6; LowerTriangularMatrix AB = Cholesky(A) * Cholesky(B); Matrix M = Cholesky(A) * B * Cholesky(A).t() - AB*AB.t(); Clean(M, 0.000000001); Print(M); M = A * Cholesky(B); M = M * M.t() - A * B * A; Clean(M, 0.000000001); Print(M); } { Tracer et1("Stage 6"); int N=49; int i; SymmetricBandMatrix S(N,1); Matrix B(N,N+1); B=0; for (i=1;i<=N;i++) { S(i,i)=1; B(i,i)=1; B(i,i+1)=-1; } for (i=1;ij) A(i,j) = 0; else if (i==j) A(i,j) = 21-i; else A(i,j) = -1; } A = A.t(); SymmetricMatrix S1; S1 << A.t() * A; SymmetricMatrix S2; S2 << A * A.t(); DiagonalMatrix D; Matrix U; Matrix V; #ifdef ATandT int anc = A.Ncols(); DiagonalMatrix I(anc); // AT&T 2.1 bug #else DiagonalMatrix I(A.Ncols()); #endif I=1.0; SVD(A,D,U,V); CheckIsSorted(D); Matrix SU = U.t() * U - I; Clean(SU,0.000000001); Print(SU); Matrix SV = V.t() * V - I; Clean(SV,0.000000001); Print(SV); Matrix B = U * D * V.t() - A; Clean(B,0.000000001); Print(B); for (i=1; i<=20; i++) D(i) -= sqrt((22.0-i)*(21.0-i)); Clean(D,0.000000001); Print(D); Jacobi(S1, D, V); CheckIsSorted(D, true); V = S1 - V * D * V.t(); Clean(V,0.000000001); Print(V); D = D.Reverse(); for (i=1; i<=20; i++) D(i) -= (22-i)*(21-i); Clean(D,0.000000001); Print(D); Jacobi(S2, D, V); CheckIsSorted(D, true); V = S2 - V * D * V.t(); Clean(V,0.000000001); Print(V); D = D.Reverse(); for (i=1; i<=20; i++) D(i) -= (22-i)*(21-i); Clean(D,0.000000001); Print(D); EigenValues(S1, D, V); CheckIsSorted(D, true); V = S1 - V * D * V.t(); Clean(V,0.000000001); Print(V); for (i=1; i<=20; i++) D(i) -= (i+1)*i; Clean(D,0.000000001); Print(D); EigenValues(S2, D, V); CheckIsSorted(D, true); V = S2 - V * D * V.t(); Clean(V,0.000000001); Print(V); for (i=2; i<=21; i++) D(i) -= (i-1)*i; Clean(D,0.000000001); Print(D); EigenValues(S1, D); CheckIsSorted(D, true); for (i=1; i<=20; i++) D(i) -= (i+1)*i; Clean(D,0.000000001); Print(D); EigenValues(S2, D); CheckIsSorted(D, true); for (i=2; i<=21; i++) D(i) -= (i-1)*i; Clean(D,0.000000001); Print(D); } { Tracer et1("Stage 3"); Matrix A(30,30); int i,j; for (i=1; i<=30; i++) for (j=1; j<=30; j++) { if (i>j) A(i,j) = 0; else if (i==j) A(i,j) = 1; else A(i,j) = -1; } Real d1 = A.LogDeterminant().Value(); DiagonalMatrix D; Matrix U; Matrix V; #ifdef ATandT int anc = A.Ncols(); DiagonalMatrix I(anc); // AT&T 2.1 bug #else DiagonalMatrix I(A.Ncols()); #endif I=1.0; SVD(A,D,U,V); CheckIsSorted(D); Matrix SU = U.t() * U - I; Clean(SU,0.000000001); Print(SU); Matrix SV = V.t() * V - I; Clean(SV,0.000000001); Print(SV); Real d2 = D.LogDeterminant().Value(); Matrix B = U * D * V.t() - A; Clean(B,0.000000001); Print(B); Real d3 = D.LogDeterminant().Value(); ColumnVector Test(3); Test(1) = d1 - 1; Test(2) = d2 - 1; Test(3) = d3 - 1; Clean(Test,0.00000001); Print(Test); // only 8 decimal figures A.ReSize(2,2); Real a = 1.5; Real b = 2; Real c = 2 * (a*a + b*b); A << a << b << a << b; I.ReSize(2); I=1; SVD(A,D,U,V); CheckIsSorted(D); SU = U.t() * U - I; Clean(SU,0.000000001); Print(SU); SV = V.t() * V - I; Clean(SV,0.000000001); Print(SV); B = U * D * V.t() - A; Clean(B,0.000000001); Print(B); D = D*D; SortDescending(D); DiagonalMatrix D50(2); D50 << c << 0; D = D - D50; Clean(D,0.000000001); Print(D); A << a << a << b << b; SVD(A,D,U,V); CheckIsSorted(D); SU = U.t() * U - I; Clean(SU,0.000000001); Print(SU); SV = V.t() * V - I; Clean(SV,0.000000001); Print(SV); B = U * D * V.t() - A; Clean(B,0.000000001); Print(B); D = D*D; SortDescending(D); D = D - D50; Clean(D,0.000000001); Print(D); } { Tracer et1("Stage 4"); // test for bug found by Olof Runborg, // Department of Numerical Analysis and Computer Science (NADA), // KTH, Stockholm Matrix A(22,20); A = 0; int a=1; A(a+0,a+2) = 1; A(a+0,a+18) = -1; A(a+1,a+9) = 1; A(a+1,a+12) = -1; A(a+2,a+11) = 1; A(a+2,a+12) = -1; A(a+3,a+10) = 1; A(a+3,a+19) = -1; A(a+4,a+16) = 1; A(a+4,a+19) = -1; A(a+5,a+17) = 1; A(a+5,a+18) = -1; A(a+6,a+10) = 1; A(a+6,a+4) = -1; A(a+7,a+3) = 1; A(a+7,a+2) = -1; A(a+8,a+14) = 1; A(a+8,a+15) = -1; A(a+9,a+13) = 1; A(a+9,a+16) = -1; A(a+10,a+8) = 1; A(a+10,a+9) = -1; A(a+11,a+1) = 1; A(a+11,a+15) = -1; A(a+12,a+16) = 1; A(a+12,a+4) = -1; A(a+13,a+6) = 1; A(a+13,a+9) = -1; A(a+14,a+5) = 1; A(a+14,a+4) = -1; A(a+15,a+0) = 1; A(a+15,a+1) = -1; A(a+16,a+14) = 1; A(a+16,a+0) = -1; A(a+17,a+7) = 1; A(a+17,a+6) = -1; A(a+18,a+13) = 1; A(a+18,a+5) = -1; A(a+19,a+7) = 1; A(a+19,a+8) = -1; A(a+20,a+17) = 1; A(a+20,a+3) = -1; A(a+21,a+6) = 1; A(a+21,a+11) = -1; Matrix U, V; DiagonalMatrix S; SVD(A, S, U, V, true, true); CheckIsSorted(S); DiagonalMatrix D(20); D = 1; Matrix tmp = U.t() * U - D; Clean(tmp,0.000000001); Print(tmp); tmp = V.t() * V - D; Clean(tmp,0.000000001); Print(tmp); tmp = U * S * V.t() - A ; Clean(tmp,0.000000001); Print(tmp); } { Tracer et1("Stage 5"); Matrix A(10,10); A.Row(1) << 1.00 << 0.07 << 0.05 << 0.00 << 0.06 << 0.09 << 0.03 << 0.02 << 0.02 << -0.03; A.Row(2) << 0.07 << 1.00 << 0.05 << 0.05 << -0.03 << 0.07 << 0.00 << 0.07 << 0.00 << 0.02; A.Row(3) << 0.05 << 0.05 << 1.00 << 0.05 << 0.02 << 0.01 << -0.05 << 0.04 << 0.05 << -0.03; A.Row(4) << 0.00 << 0.05 << 0.05 << 1.00 << -0.05 << 0.04 << 0.01 << 0.02 << -0.05 << 0.00; A.Row(5) << 0.06 << -0.03 << 0.02 << -0.05 << 1.00 << -0.03 << 0.02 << -0.02 << 0.04 << 0.00; A.Row(6) << 0.09 << 0.07 << 0.01 << 0.04 << -0.03 << 1.00 << -0.06 << 0.08 << -0.02 << -0.10; A.Row(7) << 0.03 << 0.00 << -0.05 << 0.01 << 0.02 << -0.06 << 1.00 << 0.09 << 0.12 << -0.03; A.Row(8) << 0.02 << 0.07 << 0.04 << 0.02 << -0.02 << 0.08 << 0.09 << 1.00 << 0.00 << -0.02; A.Row(9) << 0.02 << 0.00 << 0.05 << -0.05 << 0.04 << -0.02 << 0.12 << 0.00 << 1.00 << 0.02; A.Row(10) << -0.03 << 0.02 << -0.03 << 0.00 << 0.00 << -0.10 << -0.03 << -0.02 << 0.02 << 1.00; SymmetricMatrix AS; AS << A; Matrix V; DiagonalMatrix D, D1; ColumnVector Check(6); EigenValues(AS,D,V); CheckIsSorted(D, true); Check(1) = MaximumAbsoluteValue(A - V * D * V.t()); DiagonalMatrix I(10); I = 1; Check(2) = MaximumAbsoluteValue(V * V.t() - I); Check(3) = MaximumAbsoluteValue(V.t() * V - I); EigenValues(AS, D1); CheckIsSorted(D1, true); D -= D1; Clean(D,0.000000001); Print(D); Jacobi(AS,D,V); Check(4) = MaximumAbsoluteValue(A - V * D * V.t()); Check(5) = MaximumAbsoluteValue(V * V.t() - I); Check(6) = MaximumAbsoluteValue(V.t() * V - I); SortAscending(D); D -= D1; Clean(D,0.000000001); Print(D); Clean(Check,0.000000001); Print(Check); // Check loading rows SymmetricMatrix B(10); B.Row(1) << 1.00; B.Row(2) << 0.07 << 1.00; B.Row(3) << 0.05 << 0.05 << 1.00; B.Row(4) << 0.00 << 0.05 << 0.05 << 1.00; B.Row(5) << 0.06 << -0.03 << 0.02 << -0.05 << 1.00; B.Row(6) << 0.09 << 0.07 << 0.01 << 0.04 << -0.03 << 1.00; B.Row(7) << 0.03 << 0.00 << -0.05 << 0.01 << 0.02 << -0.06 << 1.00; B.Row(8) << 0.02 << 0.07 << 0.04 << 0.02 << -0.02 << 0.08 << 0.09 << 1.00; B.Row(9) << 0.02 << 0.00 << 0.05 << -0.05 << 0.04 << -0.02 << 0.12 << 0.00 << 1.00; B.Row(10) << -0.03 << 0.02 << -0.03 << 0.00 << 0.00 << -0.10 << -0.03 << -0.02 << 0.02 << 1.00; B -= AS; Print(B); } { Tracer et1("Stage 6"); // badly scaled matrix Matrix A(9,9); A.Row(1) << 1.13324e+012 << 3.68788e+011 << 3.35163e+009 << 3.50193e+011 << 1.25335e+011 << 1.02212e+009 << 3.16602e+009 << 1.02418e+009 << 9.42959e+006; A.Row(2) << 3.68788e+011 << 1.67128e+011 << 1.27449e+009 << 1.25335e+011 << 6.05413e+010 << 4.34573e+008 << 1.02418e+009 << 4.69192e+008 << 3.61098e+006; A.Row(3) << 3.35163e+009 << 1.27449e+009 << 1.25571e+007 << 1.02212e+009 << 4.34573e+008 << 3.69769e+006 << 9.42959e+006 << 3.61098e+006 << 3.59450e+004; A.Row(4) << 3.50193e+011 << 1.25335e+011 << 1.02212e+009 << 1.43514e+011 << 5.42310e+010 << 4.15822e+008 << 1.23068e+009 << 4.31545e+008 << 3.58714e+006; A.Row(5) << 1.25335e+011 << 6.05413e+010 << 4.34573e+008 << 5.42310e+010 << 2.76601e+010 << 1.89102e+008 << 4.31545e+008 << 2.09778e+008 << 1.51083e+006; A.Row(6) << 1.02212e+009 << 4.34573e+008 << 3.69769e+006 << 4.15822e+008 << 1.89102e+008 << 1.47143e+006 << 3.58714e+006 << 1.51083e+006 << 1.30165e+004; A.Row(7) << 3.16602e+009 << 1.02418e+009 << 9.42959e+006 << 1.23068e+009 << 4.31545e+008 << 3.58714e+006 << 1.12335e+007 << 3.54778e+006 << 3.34311e+004; A.Row(8) << 1.02418e+009 << 4.69192e+008 << 3.61098e+006 << 4.31545e+008 << 2.09778e+008 << 1.51083e+006 << 3.54778e+006 << 1.62552e+006 << 1.25885e+004; A.Row(9) << 9.42959e+006 << 3.61098e+006 << 3.59450e+004 << 3.58714e+006 << 1.51083e+006 << 1.30165e+004 << 3.34311e+004 << 1.25885e+004 << 1.28000e+002; SymmetricMatrix AS; AS << A; Matrix V; DiagonalMatrix D, D1; ColumnVector Check(6); EigenValues(AS,D,V); CheckIsSorted(D, true); Check(1) = MaximumAbsoluteValue(A - V * D * V.t()) / 100000; DiagonalMatrix I(9); I = 1; Check(2) = MaximumAbsoluteValue(V * V.t() - I); Check(3) = MaximumAbsoluteValue(V.t() * V - I); EigenValues(AS, D1); D -= D1; Clean(D,0.001); Print(D); Jacobi(AS,D,V); Check(4) = MaximumAbsoluteValue(A - V * D * V.t()) / 100000; Check(5) = MaximumAbsoluteValue(V * V.t() - I); Check(6) = MaximumAbsoluteValue(V.t() * V - I); SortAscending(D); D -= D1; Clean(D,0.001); Print(D); Clean(Check,0.0000001); Print(Check); } { Tracer et1("Stage 7"); // matrix with all singular values close to 1 Matrix A(8,8); A.Row(1)<<-0.4343<<-0.0445<<-0.4582<<-0.1612<<-0.3191<<-0.6784<<0.1068<<0; A.Row(2)<<0.5791<<0.5517<<0.2575<<-0.1055<<-0.0437<<-0.5282<<0.0442<<0; A.Row(3)<<0.5709<<-0.5179<<-0.3275<<0.2598<<-0.196<<-0.1451<<-0.4143<<0; A.Row(4)<<0.2785<<-0.5258<<0.1251<<-0.4382<<0.0514<<-0.0446<<0.6586<<0; A.Row(5)<<0.2654<<0.3736<<-0.7436<<-0.0122<<0.0376<<0.3465<<0.3397<<0; A.Row(6)<<0.0173<<-0.0056<<-0.1903<<-0.7027<<0.4863<<-0.0199<<-0.4825<<0; A.Row(7)<<0.0434<<0.0966<<0.1083<<-0.4576<<-0.7857<<0.3425<<-0.1818<<0; A.Row(8)<<0.0<<0.0<<0.0<<0.0<<0.0<<0.0<<0.0<<-1.0; Matrix U,V; DiagonalMatrix D; SVD(A,D,U,V); CheckIsSorted(D); Matrix B = U * D * V.t() - A; Clean(B,0.000000001); Print(B); DiagonalMatrix I(8); I = 1; D -= I; Clean(D,0.0001); Print(D); U *= U.t(); U -= I; Clean(U,0.000000001); Print(U); V *= V.t(); V -= I; Clean(V,0.000000001); Print(V); } { Tracer et1("Stage 8"); // check SortSV functions Matrix A(15, 10); int i, j; for (i = 1; i <= 15; ++i) for (j = 1; j <= 10; ++j) A(i, j) = i + j / 1000.0; DiagonalMatrix D(10); D << 0.2 << 0.5 << 0.1 << 0.7 << 0.8 << 0.3 << 0.4 << 0.7 << 0.9 << 0.6; Matrix U = A; Matrix V = 10 - 2 * A; Matrix Prod = U * D * V.t(); DiagonalMatrix D2 = D; SortDescending(D2); DiagonalMatrix D1 = D; SortSV(D1, U, V); Matrix X = D1 - D2; Print(X); X = Prod - U * D1 * V.t(); Clean(X,0.000000001); Print(X); U = A; V = 10 - 2 * A; D1 = D; SortSV(D1, U); X = D1 - D2; Print(X); D1 = D; SortSV(D1, V); X = D1 - D2; Print(X); X = Prod - U * D1 * V.t(); Clean(X,0.000000001); Print(X); D2 = D; SortAscending(D2); U = A; V = 10 - 2 * A; D1 = D; SortSV(D1, U, V, true); X = D1 - D2; Print(X); X = Prod - U * D1 * V.t(); Clean(X,0.000000001); Print(X); U = A; V = 10 - 2 * A; D1 = D; SortSV(D1, U, true); X = D1 - D2; Print(X); D1 = D; SortSV(D1, V, true); X = D1 - D2; Print(X); X = Prod - U * D1 * V.t(); Clean(X,0.000000001); Print(X); } { Tracer et1("Stage 9"); // Tom William's example Matrix A(10,10); Matrix U; Matrix V; DiagonalMatrix Sigma; Real myVals[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, }; A << myVals; SVD(A, Sigma, U, V); CheckIsSorted(Sigma); A -= U * Sigma * V.t(); Clean(A, 0.000000001); Print(A); } } newmat-1.10.4/tmtf.cpp0000644001161000116100000002400707417727422012771 0ustar rzrrzr //#define WANT_STREAM #define WANT_MATH #include "include.h" #include "newmatap.h" //#include "newmatio.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif static void SlowFT(const ColumnVector& a, const ColumnVector&b, ColumnVector& x, ColumnVector& y) { int n = a.Nrows(); x.ReSize(n); y.ReSize(n); Real f = 6.2831853071795864769/n; for (int j=1; j<=n; j++) { Real sumx = 0.0; Real sumy = 0.0; for (int k=1; k<=n; k++) { Real theta = - (j-1) * (k-1) * f; Real c = cos(theta); Real s = sin(theta); sumx += c * a(k) - s * b(k); sumy += s * a(k) + c * b(k); } x(j) = sumx; y(j) = sumy; } } static void SlowDTT_II(const ColumnVector& a, ColumnVector& c, ColumnVector& s) { int n = a.Nrows(); c.ReSize(n); s.ReSize(n); Real f = 6.2831853071795864769 / (4*n); int k; for (k=1; k<=n; k++) { Real sum = 0.0; const int k1 = k-1; // otherwise Visual C++ 5 fails for (int j=1; j<=n; j++) sum += cos(k1 * (2*j-1) * f) * a(j); c(k) = sum; } for (k=1; k<=n; k++) { Real sum = 0.0; for (int j=1; j<=n; j++) sum += sin(k * (2*j-1) * f) * a(j); s(k) = sum; } } static void SlowDTT(const ColumnVector& a, ColumnVector& c, ColumnVector& s) { int n1 = a.Nrows(); int n = n1 - 1; c.ReSize(n1); s.ReSize(n1); Real f = 6.2831853071795864769 / (2*n); int k; int sign = 1; for (k=1; k<=n1; k++) { Real sum = 0.0; for (int j=2; j<=n; j++) sum += cos((j-1) * (k-1) * f) * a(j); c(k) = sum + (a(1) + sign * a(n1)) / 2.0; sign = -sign; } for (k=2; k<=n; k++) { Real sum = 0.0; for (int j=2; j<=n; j++) sum += sin((j-1) * (k-1) * f) * a(j); s(k) = sum; } s(1) = s(n1) = 0; } static void test(int n) { Tracer et("Test FFT"); ColumnVector A(n), B(n), X, Y; for (int i=0; i q) ? p : q; } static int my_min(int p, int q) { return (p < q) ? p : q; } void BandFunctions(int l1, int u1, int l2, int u2) { int i, j; BandMatrix BM1(20, l1, u1); BM1 = 999999.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l1 && i - j >= -u1) BM1(i, j) = 100 * i + j; BandMatrix BM2 = BM1; Matrix M = BM2 - BM1; Print(M); BM2.ReSize(20, l2, u2); BM2 = 777777.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l2 && i - j >= -u2) BM2(i, j) = (100 * i + j) * 11; BandMatrix BMA = BM1 + BM2, BMS = BM1 - BM2, BMSP = SP(BM1, BM2), BMM = BM1 * BM2, BMN = -BM1; Matrix M1(20,20); M1 = 0; for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l1 && i - j >= -u1) M1(i, j) = 100 * i + j; Matrix M2(20,20); M2 = 0; for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l2 && i - j >= -u2) M2(i, j) = (100 * i + j) * 11; Matrix MA = M1 + M2, MS = M1 - M2, MSP = SP(M1, M2), MM = M1 * M2, MN = -M1; MA -= BMA; MS -= BMS; MSP -= BMSP; MM -= BMM; MN -= BMN; Print(MA); Print(MS); Print(MSP); Print(MM); Print(MN); Matrix Test(7, 2); Test(1,1) = BM1.BandWidth().Lower() - l1; Test(1,2) = BM1.BandWidth().Upper() - u1; Test(2,1) = BM2.BandWidth().Lower() - l2; Test(2,2) = BM2.BandWidth().Upper() - u2; Test(3,1) = BMA.BandWidth().Lower() - my_max(l1,l2); Test(3,2) = BMA.BandWidth().Upper() - my_max(u1,u2); Test(4,1) = BMS.BandWidth().Lower() - my_max(l1,l2); Test(4,2) = BMS.BandWidth().Upper() - my_max(u1,u2); Test(5,1) = BMSP.BandWidth().Lower() - my_min(l1,l2); Test(5,2) = BMSP.BandWidth().Upper() - my_min(u1,u2); Test(6,1) = BMM.BandWidth().Lower() - (l1 + l2); Test(6,2) = BMM.BandWidth().Upper() - (u1 + u2); Test(7,1) = BMN.BandWidth().Lower() - l1; Test(7,2) = BMN.BandWidth().Upper() - u1; Print(Test); // test element function BandMatrix BM1E(20, l1, u1); BM1E = 999999.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l1 && i - j >= -u1) BM1E.element(i-1, j-1) = 100 * i + j; BandMatrix BM2E = BM1E; BM2E.ReSize(BM2); BM2E = 777777.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l2 && i - j >= -u2) BM2E.element(i-1, j-1) = (100 * i + j) * 11; M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // test element function with constant BM1E = 444444.04; BM2E = 555555.0; const BandMatrix BM1C = BM1, BM2C = BM2; for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l1 && i - j >= -u1) BM1E.element(i-1, j-1) = BM1C.element(i-1, j-1); for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l2 && i - j >= -u2) BM2E.element(i-1, j-1) = BM2C.element(i-1, j-1); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // test subscript function with constant BM1E = 444444.04; BM2E = 555555.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l1 && i - j >= -u1) BM1E(i, j) = BM1C(i, j); for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) if (i - j <= l2 && i - j >= -u2) BM2E(i, j) = BM2C(i, j); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); } void LowerBandFunctions(int l1, int l2) { int i, j; LowerBandMatrix BM1(20, l1); BM1 = 999999.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1(i, j) = 100 * i + j; LowerBandMatrix BM2 = BM1; Matrix M = BM2 - BM1; Print(M); BM2.ReSize(20, l2); BM2 = 777777.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2(i, j) = (100 * i + j) * 11; LowerBandMatrix BMA = BM1 + BM2, BMS = BM1 - BM2, BMSP = SP(BM1, BM2), BMM = BM1 * BM2, BMN = -BM1; Matrix M1(20,20); M1 = 0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) M1(i, j) = 100 * i + j; Matrix M2(20,20); M2 = 0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) M2(i, j) = (100 * i + j) * 11; Matrix MA = M1 + M2, MS = M1 - M2, MSP = SP(M1, M2), MM = M1 * M2, MN = -M1; MA -= BMA; MS -= BMS; MSP -= BMSP; MM -= BMM; MN -= BMN; Print(MA); Print(MS); Print(MSP); Print(MM); Print(MN); Matrix Test(7, 2); Test(1,1) = BM1.BandWidth().Lower() - l1; Test(1,2) = BM1.BandWidth().Upper(); Test(2,1) = BM2.BandWidth().Lower() - l2; Test(2,2) = BM2.BandWidth().Upper(); Test(3,1) = BMA.BandWidth().Lower() - my_max(l1,l2); Test(3,2) = BMA.BandWidth().Upper(); Test(4,1) = BMS.BandWidth().Lower() - my_max(l1,l2); Test(4,2) = BMS.BandWidth().Upper(); Test(5,1) = BMSP.BandWidth().Lower() - my_min(l1,l2); Test(5,2) = BMSP.BandWidth().Upper(); Test(6,1) = BMM.BandWidth().Lower() - (l1 + l2); Test(6,2) = BMM.BandWidth().Upper(); Test(7,1) = BMN.BandWidth().Lower() - l1; Test(7,2) = BMN.BandWidth().Upper(); Print(Test); // test element function LowerBandMatrix BM1E(20, l1); BM1E = 999999.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E.element(i-1, j-1) = 100 * i + j; LowerBandMatrix BM2E = BM1E; BM2E.ReSize(BM2); BM2E = 777777.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E.element(i-1, j-1) = (100 * i + j) * 11; M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // test element function with constant BM1E = 444444.04; BM2E = 555555.0; const LowerBandMatrix BM1C = BM1, BM2C = BM2; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E.element(i-1, j-1) = BM1C.element(i-1, j-1); for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E.element(i-1, j-1) = BM2C.element(i-1, j-1); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // test subscript function with constant BM1E = 444444.04; BM2E = 555555.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E(i, j) = BM1C(i, j); for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E(i, j) = BM2C(i, j); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); } void UpperBandFunctions(int u1, int u2) { int i, j; UpperBandMatrix BM1(20, u1); BM1 = 999999.0; for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u1) BM1(i, j) = 100 * i + j; UpperBandMatrix BM2 = BM1; Matrix M = BM2 - BM1; Print(M); BM2.ReSize(20, u2); BM2 = 777777.0; for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u2) BM2(i, j) = (100 * i + j) * 11; UpperBandMatrix BMA = BM1 + BM2, BMS = BM1 - BM2, BMSP = SP(BM1, BM2), BMM = BM1 * BM2, BMN = -BM1; Matrix M1(20,20); M1 = 0; for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u1) M1(i, j) = 100 * i + j; Matrix M2(20,20); M2 = 0; for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u2) M2(i, j) = (100 * i + j) * 11; Matrix MA = M1 + M2, MS = M1 - M2, MSP = SP(M1, M2), MM = M1 * M2, MN = -M1; MA -= BMA; MS -= BMS; MSP -= BMSP; MM -= BMM; MN -= BMN; Print(MA); Print(MS); Print(MSP); Print(MM); Print(MN); Matrix Test(7, 2); Test(1,1) = BM1.BandWidth().Lower(); Test(1,2) = BM1.BandWidth().Upper() - u1; Test(2,1) = BM2.BandWidth().Lower(); Test(2,2) = BM2.BandWidth().Upper() - u2; Test(3,1) = BMA.BandWidth().Lower(); Test(3,2) = BMA.BandWidth().Upper() - my_max(u1,u2); Test(4,1) = BMS.BandWidth().Lower(); Test(4,2) = BMS.BandWidth().Upper() - my_max(u1,u2); Test(5,1) = BMSP.BandWidth().Lower(); Test(5,2) = BMSP.BandWidth().Upper() - my_min(u1,u2); Test(6,1) = BMM.BandWidth().Lower(); Test(6,2) = BMM.BandWidth().Upper() - (u1 + u2); Test(7,1) = BMN.BandWidth().Lower(); Test(7,2) = BMN.BandWidth().Upper() - u1; Print(Test); // test element function UpperBandMatrix BM1E(20, u1); BM1E = 999999.0; for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u1) BM1E.element(i-1, j-1) = 100 * i + j; UpperBandMatrix BM2E = BM1E; BM2E.ReSize(BM2); BM2E = 777777.0; for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u2) BM2E.element(i-1, j-1) = (100 * i + j) * 11; M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // test element function with constant BM1E = 444444.04; BM2E = 555555.0; const UpperBandMatrix BM1C = BM1, BM2C = BM2; for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u1) BM1E.element(i-1, j-1) = BM1C.element(i-1, j-1); for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u2) BM2E.element(i-1, j-1) = BM2C.element(i-1, j-1); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // test subscript function with constant BM1E = 444444.04; BM2E = 555555.0; for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u1) BM1E(i, j) = BM1C(i, j); for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) if (i - j >= -u2) BM2E(i, j) = BM2C(i, j); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); } void SymmetricBandFunctions(int l1, int l2) { int i, j; SymmetricBandMatrix BM1(20, l1); BM1 = 999999.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1(i, j) = 100 * i + j; SymmetricBandMatrix BM2 = BM1; Matrix M = BM2 - BM1; Print(M); BM2.ReSize(20, l2); BM2 = 777777.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2(i, j) = (100 * i + j) * 11; SymmetricBandMatrix BMA = BM1 + BM2, BMS = BM1 - BM2, BMSP = SP(BM1, BM2), BMN = -BM1; BandMatrix BMM = BM1 * BM2; SymmetricMatrix M1(20); M1 = 0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) M1(i, j) = 100 * i + j; SymmetricMatrix M2(20); M2 = 0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) M2(i, j) = (100 * i + j) * 11; SymmetricMatrix MA = M1 + M2, MS = M1 - M2, MSP = SP(M1, M2), MN = -M1; Matrix MM = M1 * M2; MA -= BMA; MS -= BMS; MSP -= BMSP; MM -= BMM; MN -= BMN; Print(MA); Print(MS); Print(MSP); Print(MM); Print(MN); Matrix Test(7, 2); Test(1,1) = BM1.BandWidth().Lower() - l1; Test(1,2) = BM1.BandWidth().Upper() - l1; Test(2,1) = BM2.BandWidth().Lower() - l2; Test(2,2) = BM2.BandWidth().Upper() - l2; Test(3,1) = BMA.BandWidth().Lower() - my_max(l1,l2); Test(3,2) = BMA.BandWidth().Upper() - my_max(l1,l2); Test(4,1) = BMS.BandWidth().Lower() - my_max(l1,l2); Test(4,2) = BMS.BandWidth().Upper() - my_max(l1,l2); Test(5,1) = BMSP.BandWidth().Lower() - my_min(l1,l2); Test(5,2) = BMSP.BandWidth().Upper() - my_min(l1,l2); Test(6,1) = BMM.BandWidth().Lower() - (l1 + l2); Test(6,2) = BMM.BandWidth().Upper() - (l1 + l2); Test(7,1) = BMN.BandWidth().Lower() - l1; Test(7,2) = BMN.BandWidth().Upper() - l1; Print(Test); // test element function SymmetricBandMatrix BM1E(20, l1); BM1E = 999999.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E.element(i-1, j-1) = 100 * i + j; SymmetricBandMatrix BM2E = BM1E; BM2E.ReSize(BM2); BM2E = 777777.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E.element(i-1, j-1) = (100 * i + j) * 11; M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // reverse subscripts BM1E = 999999.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E.element(j-1, i-1) = 100 * i + j; BM2E = 777777.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E.element(j-1, i-1) = (100 * i + j) * 11; M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // test element function with constant BM1E = 444444.04; BM2E = 555555.0; const SymmetricBandMatrix BM1C = BM1, BM2C = BM2; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E.element(i-1, j-1) = BM1C.element(i-1, j-1); for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E.element(i-1, j-1) = BM2C.element(i-1, j-1); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // reverse subscripts BM1E = 444444.0; BM2E = 555555.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E.element(j-1, i-1) = BM1C.element(j-1, i-1); for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E.element(j-1, i-1) = BM2C.element(j-1, i-1); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // test subscript function with constant BM1E = 444444.0; BM2E = 555555.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E(i, j) = BM1C(i, j); for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E(i, j) = BM2C(i, j); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // reverse subscripts BM1E = 444444.0; BM2E = 555555.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E(j, i) = BM1C(j, i); for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E(j, i) = BM2C(j, i); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); // partly reverse subscripts BM1E = 444444.0; BM2E = 555555.0; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l1) BM1E(j, i) = BM1C(i, j); for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) if (i - j <= l2) BM2E(j, i) = BM2C(i, j); M1 = BM1E - BM1; Print(M1); M2 = BM2E - BM2; Print(M2); } void trymath() { // cout << "\nSeventeenth test of Matrix package\n"; // cout << "\n"; Tracer et("Seventeenth test of Matrix package"); Tracer::PrintTrace(); { Tracer et1("Stage 1"); int i, j; BandMatrix B(8,3,1); for (i=1; i<=8; i++) for (j=-3; j<=1; j++) { int k = i+j; if (k>0 && k<=8) B(i,k) = i + k/64.0; } IdentityMatrix I(8); BandMatrix B1; B1 = I; UpperTriangularMatrix UT = I; Print(Matrix(B1-UT)); Print(Matrix(B * B - B * 2 + I - (B - I) * (B - I))); Matrix A = B; BandMatrix C; C = B; Print(Matrix(B * A - C * 2 + I - (A - I) * (B - I))); C.ReSize(8,2,2); C = 0.0; C.Inject(B); Matrix X = A.t(); B1.ReSize(8,2,2); B1.Inject(X); Print(Matrix(C.t()-B1)); Matrix BI = B.i(); A = A.i()-BI; Clean(A,0.000000001); Print(A); BandLUMatrix BLU = B.t(); BI = BLU.i(); A = X.i()-BI; Clean(A,0.000000001); Print(A); X.ReSize(1,1); X(1,1) = BLU.LogDeterminant().Value()-B.LogDeterminant().Value(); Clean(X,0.000000001); Print(X); UpperBandMatrix U; U << B; LowerBandMatrix L; L << B; DiagonalMatrix D; D << B; Print( Matrix(L + (U - D - B)) ); for (i=1; i<=8; i++) A.Column(i) << B.Column(i); Print(Matrix(A-B)); } { Tracer et1("Stage 2"); BandMatrix A(7,2,2); int i,j; for (i=1; i<=7; i++) for (j=1; j<=7; j++) { int k=i-j; if (k<0) k = -k; if (k==0) A(i,j)=6; else if (k==1) A(i,j) = -4; else if (k==2) A(i,j) = 1; A(1,1) = A(7,7) = 5; } DiagonalMatrix D(7); D = 0.0; A = A - D; BandLUMatrix B(A); Matrix M = A; ColumnVector V(6); V(1) = LogDeterminant(B).Value(); V(2) = LogDeterminant(A).Value(); V(3) = LogDeterminant(M).Value(); V(4) = Determinant(B); V(5) = Determinant(A); V(6) = Determinant(M); V = V / 64 - 1; Clean(V,0.000000001); Print(V); ColumnVector X(7); #ifdef ATandT Real a[7]; // the previous statement causes a core dump in tmti.cpp // on the HP9000 - seems very strange. Possibly the exception // mechanism is failing to track the stack correctly. If you get // this problem replace by the following statement. // Real* a = new Real [7]; if (!a) exit(1); a[0]=1; a[1]=2; a[2]=3; a[3]=4; a[4]=5; a[5]=6; a[6]=7; #else Real a[] = {1,2,3,4,5,6,7}; #endif X << a; // include these if you are using the previous dynamic definition of a //#ifdef ATandT // delete [] a; //#endif M = (M.i()*X).t() - (B.i()*X).t() * 2.0 + (A.i()*X).t(); Clean(M,0.000000001); Print(M); BandMatrix P(80,2,5); ColumnVector CX(80); for (i=1; i<=80; i++) for (j=1; j<=80; j++) { int d = i-j; if (d<=2 && d>=-5) P(i,j) = i + j/100.0; } for (i=1; i<=80; i++) CX(i) = i*100.0; Matrix MP = P; ColumnVector V1 = P.i() * CX; ColumnVector V2 = MP.i() * CX; V = V1 - V2; Clean(V,0.000000001); Print(V); V1 = P * V1; V2 = MP * V2; V = V1 - V2; Clean(V,0.000000001); Print(V); RowVector XX(1); XX = LogDeterminant(P).Value() / LogDeterminant(MP).Value() - 1.0; Clean(XX,0.000000001); Print(XX); LowerBandMatrix LP(80,5); for (i=1; i<=80; i++) for (j=1; j<=80; j++) { int d = i-j; if (d<=5 && d>=0) LP(i,j) = i + j/100.0; } MP = LP; XX.ReSize(4); XX(1) = LogDeterminant(LP).Value(); XX(2) = LogDeterminant(MP).Value(); V1 = LP.i() * CX; V2 = MP.i() * CX; V = V1 - V2; Clean(V,0.000000001); Print(V); UpperBandMatrix UP(80,4); for (i=1; i<=80; i++) for (j=1; j<=80; j++) { int d = i-j; if (d<=0 && d>=-4) UP(i,j) = i + j/100.0; } MP = UP; XX(3) = LogDeterminant(UP).Value(); XX(4) = LogDeterminant(MP).Value(); V1 = UP.i() * CX; V2 = MP.i() * CX; V = V1 - V2; Clean(V,0.000000001); Print(V); XX = XX / SumAbsoluteValue(XX) - .25; Clean(XX,0.000000001); Print(XX); } { Tracer et1("Stage 3"); SymmetricBandMatrix SA(8,5); int i,j; for (i=1; i<=8; i++) for (j=1; j<=8; j++) if (i-j<=5 && 0<=i-j) SA(i,j) =i + j/128.0; DiagonalMatrix D(8); D = 10; SA = SA + D; Matrix MA1(8,8); Matrix MA2(8,8); for (i=1; i<=8; i++) { MA1.Column(i) << SA.Column(i); MA2.Row(i) << SA.Row(i); } Print(Matrix(MA1-MA2)); D = 10; SA = SA.t() + D; MA1 = MA1 + D; Print(Matrix(MA1-SA)); UpperBandMatrix UB(8,3); LowerBandMatrix LB(8,4); D << SA; UB << SA; LB << SA; SA = SA * 5.0; D = D * 5.0; LB = LB * 5.0; UB = UB * 5.0; BandMatrix B = LB - D + UB - SA; Print(Matrix(B)); SymmetricBandMatrix A(7,2); A = 100.0; for (i=1; i<=7; i++) for (j=1; j<=7; j++) { int k=i-j; if (k==0) A(i,j)=6; else if (k==1) A(i,j) = -4; else if (k==2) A(i,j) = 1; A(1,1) = A(7,7) = 5; } BandLUMatrix C(A); Matrix M = A; ColumnVector X(8); X(1) = LogDeterminant(C).Value() - 64; X(2) = LogDeterminant(A).Value() - 64; X(3) = LogDeterminant(M).Value() - 64; X(4) = SumSquare(M) - SumSquare(A); X(5) = SumAbsoluteValue(M) - SumAbsoluteValue(A); X(6) = MaximumAbsoluteValue(M) - MaximumAbsoluteValue(A); X(7) = Trace(M) - Trace(A); X(8) = Sum(M) - Sum(A); Clean(X,0.000000001); Print(X); #ifdef ATandT Real a[7]; a[0]=1; a[1]=2; a[2]=3; a[3]=4; a[4]=5; a[5]=6; a[6]=7; #else Real a[] = {1,2,3,4,5,6,7}; #endif X.ReSize(7); X << a; X = M.i()*X - C.i()*X * 2 + A.i()*X; Clean(X,0.000000001); Print(X); LB << A; UB << A; D << A; BandMatrix XA = LB + (UB - D); Print(Matrix(XA - A)); for (i=1; i<=7; i++) for (j=1; j<=7; j++) { int k=i-j; if (k==0) A(i,j)=6; else if (k==1) A(i,j) = -4; else if (k==2) A(i,j) = 1; A(1,1) = A(7,7) = 5; } D = 1; M = LB.i() * LB - D; Clean(M,0.000000001); Print(M); M = UB.i() * UB - D; Clean(M,0.000000001); Print(M); M = XA.i() * XA - D; Clean(M,0.000000001); Print(M); Matrix MUB = UB; Matrix MLB = LB; M = LB.i() * UB - LB.i() * MUB; Clean(M,0.000000001); Print(M); M = UB.i() * LB - UB.i() * MLB; Clean(M,0.000000001); Print(M); M = LB.i() * UB - LB.i() * Matrix(UB); Clean(M,0.000000001); Print(M); M = UB.i() * LB - UB.i() * Matrix(LB); Clean(M,0.000000001); Print(M); } { // some tests about adding and subtracting band matrices of different // sizes - check bandwidth of results Tracer et1("Stage 4"); BandFunctions(9, 3, 9, 3); // equal BandFunctions(4, 7, 4, 7); // equal BandFunctions(9, 3, 5, 8); // neither < or > BandFunctions(5, 8, 9, 3); // neither < or > BandFunctions(9, 8, 5, 3); // > BandFunctions(3, 5, 8, 9); // < LowerBandFunctions(9, 9); // equal LowerBandFunctions(4, 4); // equal LowerBandFunctions(9, 5); // > LowerBandFunctions(3, 8); // < UpperBandFunctions(3, 3); // equal UpperBandFunctions(7, 7); // equal UpperBandFunctions(8, 3); // > UpperBandFunctions(5, 9); // < SymmetricBandFunctions(9, 9); // equal SymmetricBandFunctions(4, 4); // equal SymmetricBandFunctions(9, 5); // > SymmetricBandFunctions(3, 8); // < DiagonalMatrix D(6); D << 2 << 3 << 4.5 << 1.25 << 9.5 << -5; BandMatrix BD = D; UpperBandMatrix UBD; UBD = D; LowerBandMatrix LBD; LBD = D; SymmetricBandMatrix SBD = D; Matrix X = BD - D; Print(X); X = UBD - D; Print(X); X = LBD - D; Print(X); X = SBD - D; Print(X); Matrix Test(9,2); Test(1,1) = BD.BandWidth().Lower(); Test(1,2) = BD.BandWidth().Upper(); Test(2,1) = UBD.BandWidth().Lower(); Test(2,2) = UBD.BandWidth().Upper(); Test(3,1) = LBD.BandWidth().Lower(); Test(3,2) = LBD.BandWidth().Upper(); Test(4,1) = SBD.BandWidth().Lower(); Test(4,2) = SBD.BandWidth().Upper(); IdentityMatrix I(10); I *= 5; BD = I; UBD = I; LBD = I; SBD = I; X = BD - I; Print(X); X = UBD - I; Print(X); X = LBD - I; Print(X); X = SBD - I; Print(X); Test(5,1) = BD.BandWidth().Lower(); Test(5,2) = BD.BandWidth().Upper(); Test(6,1) = UBD.BandWidth().Lower(); Test(6,2) = UBD.BandWidth().Upper(); Test(7,1) = LBD.BandWidth().Lower(); Test(7,2) = LBD.BandWidth().Upper(); Test(8,1) = SBD.BandWidth().Lower(); Test(8,2) = SBD.BandWidth().Upper(); RowVector RV = D.AsRow(); I.ReSize(6); BandMatrix BI = I; I = 1; BD = RV.AsDiagonal() + BI; X = BD - D - I; Print(X); Test(9,1) = BD.BandWidth().Lower(); Test(9,2) = BD.BandWidth().Upper(); Print(Test); } { // various element functions Tracer et1("Stage 5"); int i, j; Matrix Count(1, 1); Count = 0; // for counting errors Matrix M(20,30); for (i = 1; i <= 20; ++i) for (j = 1; j <= 30; ++j) M(i, j) = 100 * i + j; const Matrix CM = M; for (i = 1; i <= 20; ++i) for (j = 1; j <= 30; ++j) { if (M(i, j) != CM(i, j)) ++Count(1,1); if (M(i, j) != CM.element(i-1, j-1)) ++Count(1,1); if (M(i, j) != M.element(i-1, j-1)) ++Count(1,1); } UpperTriangularMatrix U(20); for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) U(i, j) = 100 * i + j; const UpperTriangularMatrix CU = U; for (i = 1; i <= 20; ++i) for (j = i; j <= 20; ++j) { if (U(i, j) != CU(i, j)) ++Count(1,1); if (U(i, j) != CU.element(i-1, j-1)) ++Count(1,1); if (U(i, j) != U.element(i-1, j-1)) ++Count(1,1); } LowerTriangularMatrix L(20); for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) L(i, j) = 100 * i + j; const LowerTriangularMatrix CL = L; for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) { if (L(i, j) != CL(i, j)) ++Count(1,1); if (L(i, j) != CL.element(i-1, j-1)) ++Count(1,1); if (L(i, j) != L.element(i-1, j-1)) ++Count(1,1); } SymmetricMatrix S(20); for (i = 1; i <= 20; ++i) for (j = 1; j <= i; ++j) S(i, j) = 100 * i + j; const SymmetricMatrix CS = S; for (i = 1; i <= 20; ++i) for (j = 1; j <= 20; ++j) { if (S(i, j) != CS(i, j)) ++Count(1,1); if (S(i, j) != CS.element(i-1, j-1)) ++Count(1,1); if (S(i, j) != S.element(i-1, j-1)) ++Count(1,1); if (S(i, j) != S(j, i)) ++Count(1,1); if (S(i, j) != CS(i, j)) ++Count(1,1); if (S(i, j) != CS.element(i-1, j-1)) ++Count(1,1); if (S(i, j) != S.element(i-1, j-1)) ++Count(1,1); } DiagonalMatrix D(20); for (i = 1; i <= 20; ++i) D(i) = 100 * i + i * i; const DiagonalMatrix CD = D; for (i = 1; i <= 20; ++i) { if (D(i, i) != CD(i, i)) ++Count(1,1); if (D(i, i) != CD.element(i-1, i-1)) ++Count(1,1); if (D(i, i) != D.element(i-1, i-1)) ++Count(1,1); if (D(i, i) != D(i)) ++Count(1,1); if (D(i) != CD(i)) ++Count(1,1); if (D(i) != CD.element(i-1)) ++Count(1,1); if (D(i) != D.element(i-1)) ++Count(1,1); } RowVector R(20); for (i = 1; i <= 20; ++i) R(i) = 100 * i + i * i; const RowVector CR = R; for (i = 1; i <= 20; ++i) { if (R(i) != CR(i)) ++Count(1,1); if (R(i) != CR.element(i-1)) ++Count(1,1); if (R(i) != R.element(i-1)) ++Count(1,1); } ColumnVector C(20); for (i = 1; i <= 20; ++i) C(i) = 100 * i + i * i; const ColumnVector CC = C; for (i = 1; i <= 20; ++i) { if (C(i) != CC(i)) ++Count(1,1); if (C(i) != CC.element(i-1)) ++Count(1,1); if (C(i) != C.element(i-1)) ++Count(1,1); } Print(Count); } { // resize to another matrix size Tracer et1("Stage 6"); Matrix A(20, 30); A = 3; Matrix B(3, 4); B.ReSize(A); B = 6; B -= 2 * A; Print(B); A.ReSize(25,25); A = 12; UpperTriangularMatrix U(5); U.ReSize(A); U = 12; U << (U - A); Print(U); LowerTriangularMatrix L(5); L.ReSize(U); L = 12; L << (L - A); Print(L); DiagonalMatrix D(5); D.ReSize(U); D = 12; D << (D - A); Print(D); SymmetricMatrix S(5); S.ReSize(U); S = 12; S << (S - A); Print(S); IdentityMatrix I(5); I.ReSize(U); I = 12; D << (I - A); Print(D); A.ReSize(10, 1); A = 17; ColumnVector C(5); C.ReSize(A); C = 17; C -= A; Print(C); A.ReSize(1, 10); A = 15; RowVector R(5); R.ReSize(A); R = 15; R -= A; Print(R); } { // generic matrix and identity matrix Tracer et1("Stage 7"); IdentityMatrix I(5); I *= 4; GenericMatrix GM = I; GM /= 2; DiagonalMatrix D = GM; Matrix A = GM + 10; A -= 10; A -= D; Print(A); } { // SP and upper and lower triangular matrices Tracer et1("Stage 8"); UpperTriangularMatrix UT(4); UT << 3 << 7 << 3 << 9 << 5 << 2 << 6 << 8 << 0 << 4; LowerTriangularMatrix LT; LT.ReSize(UT); LT << 2 << 7 << 9 << 2 << 8 << 6 << 1 << 0 << 3 << 5; DiagonalMatrix D = SP(UT, LT); DiagonalMatrix D1(4); D1 << 6 << 45 << 48 << 20; D -= D1; Print(D); BandMatrix BM = SP(UT, LT); Matrix X = BM - D1; Print(X); RowVector RV(2); RV(1) = BM.BandWidth().Lower(); RV(2) = BM.BandWidth().Upper(); Print(RV); } // cout << "\nEnd of Seventeenth test\n"; } newmat-1.10.4/tmti.cpp0000644001161000116100000001367207411246636012777 0ustar rzrrzr //#define WANT_STREAM #include "include.h" #include "newmatap.h" //#include "newmatio.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif void WillNotConverge() { Matrix A(10,10); Throw(ConvergenceException(A)); } void ReSizeMatrix(Matrix& A) // for seeing if we can redimension a vector as a matrix { A.ReSize(4,5); } void trymati() { #ifndef DisableExceptions Tracer et("Eighteenth test of Matrix package"); Matrix RUStillThere(10,20); RUStillThere = 1553; Tracer::PrintTrace(); ColumnVector checks(23); checks = 1.0; checks(1) = 0.0; Try { WillNotConverge(); } Catch(ConvergenceException) { checks(2) = 0; } CatchAll { checks(1) = 1; } Try { Matrix M(10,10); SymmetricMatrix S = M; } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(3) = 0; } CatchAll { checks(1) = 1; } Try { Matrix M(10,10); M(10,11) = 2.0; } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(IndexException) { checks(4) = 0; } CatchAll { checks(1) = 1; } Try { Matrix M(10,10); M = 0.0; M = M.i(); } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(1) = 1; } Catch(SingularException) { checks(5) = 0; } Catch(Bad_alloc) { checks(1) = 1; } CatchAndThrow; Try { ColumnVector A(30), B(50); A = 5; B = 3; FFT(A,B,A,B); } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(6) = 0; } CatchAll { checks(1) = 1; } Try { ColumnVector A(30); A = 5; Matrix At = A.t(); DiagonalMatrix D; SVD(At,D); } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(Logic_error) { checks(6) = 0; } Catch(Bad_alloc) { checks(1) = 1; } CatchAndThrow; Try { BandMatrix X(10,3,4); X(1,10) = 4.0; } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(IndexException) { checks(7) = 0; } CatchAll { checks(1) = 1; } Try { SymmetricMatrix S(10); S = 5; LowerTriangularMatrix L = Cholesky(S); } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(1) = 1; } Catch(NPDException) { checks(8) = 0; } Catch(Bad_alloc) { checks(1) = 1; } CatchAndThrow; Try { BandMatrix M(10,3,5); M = 0.0; Matrix XM = M.i(); } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(1) = 1; } Catch(SingularException) { checks(9) = 0; } Catch(Bad_alloc) { checks(1) = 1; } CatchAndThrow; Try { ColumnVector X(10); ColumnVector Y; X = 5; X = X - Y; } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(IncompatibleDimensionsException) { checks(10) = 0; } Catch(Bad_alloc) { checks(1) = 1; } CatchAndThrow; Try { UpperTriangularMatrix U(3); RowVector RV(3); RV = 10; U.Row(2) = RV; } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(11) = 0; } Catch(Bad_alloc) { checks(1) = 1; } CatchAndThrow; Try { DiagonalMatrix D(3); D << 12 << 13 << 14 << 15; } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(12) = 0; } CatchAndThrow; Try { ColumnVector D(3); D << 12 << 13; D << 1 << 2 << 3; } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(13) = 0; } CatchAndThrow; Try { { ColumnVector D(3); D << 12 << 13; } } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(14) = 0; } CatchAndThrow; Try { ColumnVector CV; ReSizeMatrix(CV); } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(VectorException) { checks(15) = 0; } CatchAndThrow; Try { RowVector RV(20); ReSizeMatrix(RV); } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(VectorException) { checks(16) = 0; } CatchAndThrow; Try { UpperTriangularMatrix U(10); U = 5; DiagonalMatrix D(10); D = 2; D += U; // illegal conversion } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(17) = 0; } CatchAndThrow; Try { Matrix A(2,3), B(2,3); if (A < B) A = B; } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(NotDefinedException) { checks(18) = 0; } CatchAndThrow; Try { SymmetricBandMatrix A(3,1); A = 1; A = A.Reverse(); } Catch(ConvergenceException) { checks(1) = 1; } Catch(InternalException) { checks(1) = 1; } Catch(NotDefinedException) { checks(19) = 0; } CatchAndThrow; Try { Matrix A(5,5); A = 1.0; UpperTriangularMatrix B(10); B.SubMatrix(3,7,3,7) = A; } Catch(ProgramException) { checks(20) = 0; } CatchAndThrow; Try { { RowVector D(1); D << 12 << 13; } } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(21) = 0; } CatchAndThrow; Try { { RowVector D(0); D << 12; } } Catch(InternalException) { checks(1) = 1; } Catch(ProgramException) { checks(22) = 0; } CatchAndThrow; Try { Matrix M(10,10); Matrix XM(3,3); M = 0.0; XM = M.i(); } Catch(SingularException) { checks(23) = 0; } CatchAll { checks(1) = 1; } Print(checks); Matrix RUStillThere1(10,20); RUStillThere1 = 1553; RUStillThere = RUStillThere - RUStillThere1; Print(RUStillThere); #endif } newmat-1.10.4/tmtj.cpp0000644001161000116100000001106507415277350012773 0ustar rzrrzr //#define WANT_STREAM #include "include.h" #include "newmatap.h" //#include "newmatio.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif void trymatj() { Tracer et("Nineteenth test of Matrix package"); Tracer::PrintTrace(); // testing elementwise (SP) products { Tracer et1("Stage 1"); Matrix A(13,7), B(13,7), C(13,7); int i,j; for (i=1;i<=13;i++) for (j=1; j<=7; j++) { Real a = (i+j*j)/2, b = (i*j-i/4); A(i,j)=a; B(i,j)=b; C(i,j)=a*b; } // Where complete matrix routine can be used Matrix X = SP(A,B)-C; Print(X); X = SP(A,B+1.0)-A-C; Print(X); X = SP(A-1,B)+B-C; Print(X); X = SP(A-1,B+1)+B-A-C+1; Print(X); // Where row-wise routine will be used A = A.Rows(7,13); B = B.Rows(7,13); C = C.Rows(7,13); LowerTriangularMatrix LTA; LTA << A; UpperTriangularMatrix UTB; UTB << B; DiagonalMatrix DC; DC << C; X = SP(LTA,UTB) - DC; Print(X); X = SP(LTA*2,UTB) - DC*2; Print(X); X = SP(LTA, UTB /2) - DC/2; Print(X); X = SP(LTA/2, UTB*2) - DC; Print(X); DiagonalMatrix DX; DX << SP(A,B); DX << (DX-C); Print(DX); DX << SP(A*4,B); DX << (DX-C*4); Print(DX); DX << SP(A,B*2); DX << (DX-C*2); Print(DX); DX << SP(A/4,B/4); DX << (DX-C/16); Print(DX); LowerTriangularMatrix LX; LX = SP(LTA,B); LX << (LX-C); Print(LX); LX = SP(LTA*3,B); LX << (LX-C*3); Print(LX); LX = SP(LTA,B*5); LX << (LX-C*5); Print(LX); LX = SP(-LTA,-B); LX << (LX-C); Print(LX); } { // Symmetric Matrices Tracer et1("Stage 2"); SymmetricMatrix A(25), B(25), C(25); int i,j; for (i=1;i<=25;i++) for (j=i;j<=25;j++) { Real a = i*j +i - j + 3; Real b = i * i + j; A(i,j)=a; B(i,j)=b; C(i,j)=a*b; } UpperTriangularMatrix UT; UT << SP(A,B); UT << (UT - C); Print(UT); Matrix MA = A, X; X = SP(MA,B)-C; Print(X); X = SP(A,B)-C; Print(X); SymmetricBandMatrix BA(25,5), BB(25,5), BC(25,5); BA.Inject(A); BB.Inject(B); BC.Inject(C); X = SP(BA,BB)-BC; Print(X); X = SP(BA*7,BB)-BC*7; Print(X); X = SP(BA,BB/8)-BC/8; Print(X); X = SP(BA*16,BB/16)-BC; Print(X); X = SP(BA,BB); X=X-BC; Print(X); X = SP(BA*2, BB/2)-BC; Print(X); X = SP(BA, BB/2)-BC/2; Print(X); X = SP(BA*2, BB)-BC*2; Print(X); } { // Band matrices Tracer et1("Stage 3"); Matrix A(19,19), B(19,19), C(19,19); int i,j; for (i=1;i<=19;i++) for (j=1;j<=19;j++) { Real a = i*j +i - 1.5*j + 3; Real b = i * i + j; A(i,j)=a; B(i,j)=b; C(i,j)=a*b; } BandMatrix BA(19,10,7), BB(19,8,15), BC(19,8,7); BA.Inject(A); BB.Inject(B); BC.Inject(C); Matrix X; BandMatrix BX; ColumnVector BW(2); X = SP(BA,BB); X=X-BC; Print(X); X = SP(BA/8,BB); X=X-BC/8; Print(X); X = SP(BA,BB*17); X=X-BC*17; Print(X); X = SP(BA/4,BB*7); X=X-BC*7/4; Print(X); X = SP(BA,BB)-BC; Print(X); X = SP(BA/8,BB)-BC/8; Print(X); X = SP(BA,BB*17)-BC*17; Print(X); X = SP(BA/4,BB*7)-BC*7/4; Print(X); BX = SP(BA,BB); BW(1)=BX.upper-7; BW(2)=BX.lower-8; Print(BW); BA.ReSize(19,7,10); BB.ReSize(19,15,8); BC.ReSize(19,7,8); BA.Inject(A); BB.Inject(B); BC.Inject(C); X = SP(BA,BB); X=X-BC; Print(X); X = SP(BA/8,BB); X=X-BC/8; Print(X); X = SP(BA,BB*17); X=X-BC*17; Print(X); X = SP(BA/4,BB*7); X=X-BC*7/4; Print(X); X = SP(BA,BB)-BC; Print(X); X = SP(BA/8,BB)-BC/8; Print(X); X = SP(BA,BB*17)-BC*17; Print(X); X = SP(BA/4,BB*7)-BC*7/4; Print(X); BX = SP(BA,BB); BW(1)=BX.upper-8; BW(2)=BX.lower-7; Print(BW); } { // SymmetricBandMatrices Tracer et1("Stage 4"); Matrix A(7,7), B(7,7); int i,j; for (i=1;i<=7;i++) for (j=1;j<=7;j++) { Real a = i*j +i - 1.5*j + 3; Real b = i * i + j; A(i,j)=a; B(i,j)=b; } BandMatrix BA(7,2,4), BB(7,3,1), BC(7,2,1); BA.Inject(A); SymmetricBandMatrix SB(7,3); SymmetricMatrix S; S << (B+B.t()); SB.Inject(S); A = BA; S = SB; Matrix X; X = SP(BA,SB); X=X-SP(A,S); Print(X); X = SP(BA*2,SB); X=X-SP(A,S*2); Print(X); X = SP(BA,SB/4); X=X-SP(A/4,S); Print(X); X = SP(BA*4,SB/4); X=X-SP(A,S); Print(X); X = SP(BA,SB)-SP(A,S); Print(X); X = SP(BA*2,SB)-SP(A,S*2); Print(X); X = SP(BA,SB/4)-SP(A/4,S); Print(X); X = SP(BA*4,SB/4)-SP(A,S); Print(X); } } newmat-1.10.4/tmtk.cpp0000644001161000116100000001232507423733500012765 0ustar rzrrzr #define WANT_STREAM #include "include.h" #include "newmatap.h" #include "newmatio.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif static inline int my_min(int x, int y) { return x < y ? x : y; } static inline int my_max(int x, int y) { return x > y ? x : y; } #ifdef SETUP_C_SUBSCRIPTS void trymatk() { Tracer et("Twentieth test of Matrix package"); Tracer::PrintTrace(); // test C subscript package int i,j; Matrix X, Y; cout << "Matrix\n"; Matrix A(15,35), B(15, 35); for (i=0; i<15; i++) for (j=0; j<35; j++) { A[i][j] = i+100*j; B(i+1,j+1) = i+100*j; } X = A - B; Print(X); Y = X; for (i=0; i<15; i++) for (j=0; j<35; j++) { X.element(i,j) = A.element(i,j) - B[i][j]; Y.element(i,j) = ((const Matrix&)A)[i][j] - B[i][j]; } Print(X); Print(Y); A.CleanUp(); B.CleanUp(); cout << "UpperTriangularMatrix\n"; UpperTriangularMatrix A1(15), B1(15); for (i=0; i<15; i++) for (j=i; j<15; j++) { A1[i][j] = i+100*j; B1(i+1,j+1) = i+100*j; } X = A1 - B1; Print(X); Y = X; for (i=0; i<15; i++) for (j=i; j<15; j++) { X.element(i,j) = A1.element(i,j) - B1[i][j]; Y.element(i,j) = ((const UpperTriangularMatrix&)A1)[i][j] - B1[i][j]; } Print(X); Print(Y); A1.CleanUp(); B1.CleanUp(); cout << "LowerTriangularMatrix\n"; LowerTriangularMatrix A2(35), B2(35); for (i=0; i<35; i++) for (j=0; j<=i; j++) { A2[i][j] = i+100*j; B2(i+1,j+1) = i+100*j; } X = A2 - B2; Print(X); Y = X; for (i=0; i<35; i++) for (j=0; j<=i; j++) { X.element(i,j) = A2.element(i,j) - B2[i][j]; Y.element(i,j) = ((const LowerTriangularMatrix&)A2)[i][j] - B2[i][j]; } Print(X); Print(Y); A2.CleanUp(); B2.CleanUp(); cout << "SymmetricMatrix\n"; SymmetricMatrix A3(10), B3(10); for (i=0; i<10; i++) for (j=0; j<=i; j++) { A3[i][j] = i+100*j; B3(i+1,j+1) = i+100*j; } X = A3 - B3; Print(X); Y = X; for (i=0; i<10; i++) for (j=0; j<=i; j++) { X.element(i,j) = A3.element(i,j) - B3[i][j]; Y.element(i,j) = ((const SymmetricMatrix&)A3)[i][j] - B3[i][j]; } Print(X); Print(Y); A3.CleanUp(); B3.CleanUp(); cout << "DiagonalMatrix\n"; DiagonalMatrix A4(10), B4(10); for (i=0; i<10; i++) { A4[i] = i+100; B4(i+1) = i+100; } X = A4 - B4; Print(X); Y = X; for (i=0; i<10; i++) { X.element(i,i) = A4.element(i) - B4[i]; Y.element(i,i) = ((const DiagonalMatrix&)A4)[i] - B4[i]; } Print(X); Print(Y); A4.CleanUp(); B4.CleanUp(); cout << "RowVector\n"; RowVector A5(10), B5(10); for (i=0; i<10; i++) { A5[i] = i+100; B5(i+1) = i+100; } X = A5 - B5; Print(X); Y = X; for (i=0; i<10; i++) { X.element(0,i) = A5.element(i) - B5[i]; Y.element(0,i) = ((const RowVector&)A5)[i] - B5[i]; } Print(X); Print(Y); A5.CleanUp(); B5.CleanUp(); cout << "ColumnVector\n"; ColumnVector A6(10), B6(10); for (i=0; i<10; i++) { A6[i] = i+100; B6(i+1) = i+100; } X = A6 - B6; Print(X); Y = X; for (i=0; i<10; i++) { X.element(i,0) = A6.element(i) - B6[i]; Y.element(i,0) = ((const ColumnVector&)A6)[i] - B6[i]; } Print(X); Print(Y); A6.CleanUp(); B6.CleanUp(); cout << "BandMatrix\n"; BandMatrix A7(55,10, 5), B7(55, 10, 5); for (i=0; i<55; i++) for (j=my_max(0,i-10); j<=my_min(54,i+5); j++) { A7[i][j] = i+100*j; B7(i+1,j+1) = i+100*j; } X = A7 - B7; Print(X); Y = X; for (i=0; i<55; i++) for (j=my_max(0,i-10); j<=my_min(54,i+5); j++) { X.element(i,j) = A7.element(i,j) - B7[i][j]; Y.element(i,j) = ((const BandMatrix&)A7)[i][j] - B7[i][j]; } Print(X); Print(Y); A7.CleanUp(); B7.CleanUp(); cout << "UpperBandMatrix\n"; UpperBandMatrix A8(80,15), B8(80,15); for (i=0; i<80; i++) for (j=i; j<=my_min(79,i+15); j++) { A8[i][j] = i+100*j; B8(i+1,j+1) = i+100*j; } X = A8 - B8; Print(X); Y = X; for (i=0; i<80; i++) for (j=i; j<=my_min(79,i+15); j++) { X.element(i,j) = A8.element(i,j) - B8[i][j]; Y.element(i,j) = ((const UpperBandMatrix&)A8)[i][j] - B8[i][j]; } Print(X); Print(Y); A8.CleanUp(); B8.CleanUp(); cout << "LowerBandMatrix\n"; LowerBandMatrix A9(75,27), B9(75,27); for (i=0; i<75; i++) for (j=my_max(0,i-27); j<=i; j++) { A9[i][j] = i+100*j; B9(i+1,j+1) = i+100*j; } X = A9 - B9; Print(X); Y = X; for (i=0; i<75; i++) for (j=my_max(0,i-27); j<=i; j++) { X.element(i,j) = A9.element(i,j) - B9[i][j]; Y.element(i,j) = ((const LowerBandMatrix&)A9)[i][j] - B9[i][j]; } Print(X); Print(Y); A9.CleanUp(); B9.CleanUp(); cout << "SymmetricBandMatrix\n"; SymmetricBandMatrix Aa(69,15), Ba(69,15); for (i=0; i<69; i++) for (j=my_max(0,i-15); j<=i; j++) { Aa[i][j] = i+100*j; Ba(i+1,j+1) = i+100*j; } X = Aa - Ba; Print(X); Y = X; for (i=0; i<69; i++) for (j=my_max(0,i-15); j<=i; j++) { X.element(i,j) = Aa.element(i,j) - Ba[i][j]; Y.element(i,j) = ((const SymmetricBandMatrix&)Aa)[i][j] - Ba[i][j]; } Print(X); Print(Y); Aa.CleanUp(); Ba.CleanUp(); } #else void trymatk() { Tracer et("Twentieth test of Matrix package"); Tracer::PrintTrace(); // test C subscript package cout << "C subscripts not enabled, not tested\n\n"; } #endif newmat-1.10.4/tmtl.cpp0000644001161000116100000001201507205446502012763 0ustar rzrrzr #define WANT_STREAM #define WANT_MATH #include "newmat.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif // test maxima and minima Real TestMax(const GenericMatrix& GM) { Matrix M = GM; ColumnVector CV = GM.AsColumn(); int c, i, j, k; int n = CV.Nrows(), nr = M.Nrows(), nc = M.Ncols(); Real x1, x2, x3; MatrixBandWidth mbw = GM.BandWidth(); int u = mbw.Upper(); int l = mbw.Lower(); bool IsBandMatrix = u > 0 && l > 0 && !(u == 0 && l == 0); x1 = GM.MaximumAbsoluteValue(); x2 = GM.MaximumAbsoluteValue1(i); if (fabs(CV(i)) != x2) return 1.1; x3 = GM.MaximumAbsoluteValue2(i,j); if (fabs(M(i,j)) != x3) return 1.2; if (x3 != x1) return 1.3; if (x2 != x1) return 1.4; c = 0; for (k = 1; k <= n; k++) { Real cvk = fabs(CV(k)); if (x1 <= cvk) { if (x1 < cvk) return 1.5; else c++; } } if (c == 0) return 1.6; x1 = GM.MinimumAbsoluteValue(); x2 = GM.MinimumAbsoluteValue1(i); if (fabs(CV(i)) != x2) return 2.1; x3 = GM.MinimumAbsoluteValue2(i,j); if (fabs(M(i,j)) != x3) return 2.2; if (x3 != x1) return 2.3; if (x2 != CV.MinimumAbsoluteValue()) return 2.4; c = 0; if (IsBandMatrix) { for (i = 1; i <= nr; i++) for (j = 1; j <= nc; j++) if (i - j <= l && j - i <= u) { Real mij = fabs(M(i,j)); if (x1 >= mij) { if (x1 > mij) return 2.51; else c++; } } } else { for (k = 1; k <= n; k++) { Real cvk = fabs(CV(k)); if (x1 >= cvk) { if (x1 > cvk) return 2.52; else c++; } } } if (c == 0) return 2.6; x1 = GM.Maximum(); x2 = GM.Maximum1(i); if (CV(i) != x2) return 3.1; x3 = GM.Maximum2(i,j); if (M(i,j) != x3) return 3.2; if (x3 != x1) return 3.3; if (x2 != CV.Maximum()) return 3.4; c = 0; if (IsBandMatrix) { for (i = 1; i <= nr; i++) for (j = 1; j <= nc; j++) if (i - j <= l && j - i <= u) { Real mij = M(i,j); if (x1 <= mij) { if (x1 < mij) return 3.51; else c++; } } } else { for (k = 1; k <= n; k++) { Real cvk = CV(k); if (x1 <= cvk) { if (x1 < cvk) return 3.52; else c++; } } } if (c == 0) return 3.6; x1 = GM.Minimum(); x2 = GM.Minimum1(i); if (CV(i) != x2) return 4.1; x3 = GM.Minimum2(i,j); if (M(i,j) != x3) return 4.2; if (x3 != x1) return 4.3; if (x2 != CV.Minimum()) return 4.4; c = 0; if (IsBandMatrix) { for (i = 1; i <= nr; i++) for (j = 1; j <= nc; j++) if (i - j <= l && j - i <= u) { Real mij = M(i,j); if (x1 >= mij) { if (x1 > mij) return 4.51; else c++; } } } else { for (k = 1; k <= n; k++) { Real cvk = CV(k); if (x1 >= cvk) { if (x1 > cvk) return 4.52; else c++; } } } if (c == 0) return 4.6; return 0; } void trymatl() { Tracer et("Twenty first test of Matrix package"); Tracer::PrintTrace(); Matrix M(4, 4); M << 1.5 << 1.0 << -4.0 << 4.5 << 3.5 << 7.0 << 2.0 << -1.0 << -1.5 << 7.5 << -6.0 << 5.0 << 0.5 << -8.0 << 5.5 << 4.0; UpperTriangularMatrix UM; UM << M; LowerTriangularMatrix LM; LM << -M; SymmetricMatrix SM; SM << (UM + UM.t()); BandMatrix BM(4, 1, 2); BM.Inject(M); DiagonalMatrix DM; DM << M; SymmetricBandMatrix SBM(4,1); SBM.Inject(M); RowVector Test(28); int k = 0; // tests for different shapes Test(++k) = TestMax(GenericMatrix(M)); Test(++k) = TestMax(GenericMatrix(UM)); Test(++k) = TestMax(GenericMatrix(LM)); Test(++k) = TestMax(GenericMatrix(SM)); Test(++k) = TestMax(GenericMatrix(DM)); Test(++k) = TestMax(GenericMatrix(BM)); Test(++k) = TestMax(GenericMatrix(SBM)); // tests for constant matrices - don't put non-zeros in corners of BM Matrix MX(4,4); MX = 1; Test(++k) = TestMax(GenericMatrix(MX)); BM.Inject(MX); Test(++k) = TestMax(GenericMatrix(BM)); MX = 0; Test(++k) = TestMax(GenericMatrix(MX)); BM.Inject(MX); Test(++k) = TestMax(GenericMatrix(BM)); MX = -1; Test(++k) = TestMax(GenericMatrix(MX)); BM.Inject(MX); Test(++k) = TestMax(GenericMatrix(BM)); // test for non-square MX = M | (2 * M).t(); Test(++k) = TestMax(GenericMatrix(MX)); // test on row and column vector RowVector RV(6); RV << 1 << 3 << -5 << 2 << -4 << 3; Test(++k) = TestMax(GenericMatrix(RV)); Test(++k) = TestMax(GenericMatrix(RV.t())); // test for function form Test(++k) = (MaximumAbsoluteValue(RV) - 5); Test(++k) = (MinimumAbsoluteValue(RV) - 1); Test(++k) = (Maximum(RV) - 3); Test(++k) = (Minimum(RV) + 5); Test(++k) = (MaximumAbsoluteValue(-RV) - 5); Test(++k) = (MinimumAbsoluteValue(-RV) - 1); Test(++k) = (Maximum(-RV) - 5); Test(++k) = (Minimum(-RV) + 3); // test formulae RowVector RV2(6); RV2 << 2 << 8 << 1 << 9 << 3 << -1; Test(++k) = (MaximumAbsoluteValue(RV+RV2) - 11); Test(++k) = (MinimumAbsoluteValue(RV+RV2) - 1); Test(++k) = (Maximum(RV+RV2) - 11); Test(++k) = (Minimum(RV+RV2) + 4); Print(Test); } newmat-1.10.4/tmtm.cpp0000644001161000116100000001447707550523650013005 0ustar rzrrzr #define WANT_STREAM #define WANT_MATH #include "newmat.h" #include "tmt.h" #ifdef use_namespace using namespace NEWMAT; #endif // test Kronecker Product void trymatm() { Tracer et("Twenty second test of Matrix package"); Tracer::PrintTrace(); { Tracer et1("Stage 1"); Matrix A(2,3); A << 3 << 5 << 2 << 4 << 1 << 6; Matrix B(4,3); B << 7 << 2 << 9 << 1 << 3 << 6 << 4 << 10 << 5 << 11 << 8 << 12; Matrix C(8, 9); C.Row(1) << 21 << 6 << 27 << 35 << 10 << 45 << 14 << 4 << 18; C.Row(2) << 3 << 9 << 18 << 5 << 15 << 30 << 2 << 6 << 12; C.Row(3) << 12 << 30 << 15 << 20 << 50 << 25 << 8 << 20 << 10; C.Row(4) << 33 << 24 << 36 << 55 << 40 << 60 << 22 << 16 << 24; C.Row(5) << 28 << 8 << 36 << 7 << 2 << 9 << 42 << 12 << 54; C.Row(6) << 4 << 12 << 24 << 1 << 3 << 6 << 6 << 18 << 36; C.Row(7) << 16 << 40 << 20 << 4 << 10 << 5 << 24 << 60 << 30; C.Row(8) << 44 << 32 << 48 << 11 << 8 << 12 << 66 << 48 << 72; Matrix AB = KP(A,B) - C; Print(AB); IdentityMatrix I1(10); IdentityMatrix I2(15); I2 *= 2; DiagonalMatrix D = KP(I1, I2) - IdentityMatrix(150) * 2; Print(D); } { Tracer et1("Stage 2"); UpperTriangularMatrix A(3); A << 3 << 8 << 5 << 7 << 2 << 4; UpperTriangularMatrix B(4); B << 4 << 1 << 7 << 2 << 3 << 9 << 8 << 1 << 5 << 6; UpperTriangularMatrix C(12); C.Row(1) <<12<< 3<<21<< 6 <<32<< 8<<56<<16 <<20<< 5<<35<<10; C.Row(2) << 9<<27<<24 << 0<<24<<72<<64 << 0<<15<<45<<40; C.Row(3) << 3<<15 << 0<< 0<< 8<<40 << 0<< 0<< 5<<25; C.Row(4) <<18 << 0<< 0<< 0<<48 << 0<< 0<< 0<<30; C.Row(5) <<28<< 7<<49<<14 << 8<< 2<<14<< 4; C.Row(6) <<21<<63<<56 << 0<< 6<<18<<16; C.Row(7) << 7<<35 << 0<< 0<< 2<<10; C.Row(8) <<42 << 0<< 0<< 0<<12; C.Row(9) <<16<< 4<<28<< 8; C.Row(10) <<12<<36<<32; C.Row(11) << 4<<20; C.Row(12) <<24; UpperTriangularMatrix AB = KP(A,B) - C; Print(AB); LowerTriangularMatrix BT = B.t(); Matrix N(12,12); N.Row(1) <<12 << 0<< 0<< 0 <<32<< 0<< 0<< 0 <<20<< 0<< 0<< 0; N.Row(2) << 3 << 9<< 0<< 0 << 8<<24<< 0<< 0 << 5<<15<< 0<< 0; N.Row(3) <<21 <<27<< 3<< 0 <<56<<72<< 8<< 0 <<35<<45<< 5<< 0; N.Row(4) << 6 <<24<<15<<18 <<16<<64<<40<<48 <<10<<40<<25<<30; N.Row(5) << 0 << 0<< 0<< 0 <<28<< 0<< 0<< 0 << 8<< 0<< 0<< 0; N.Row(6) << 0 << 0<< 0<< 0 << 7<<21<< 0<< 0 << 2<< 6<< 0<< 0; N.Row(7) << 0 << 0<< 0<< 0 <<49<<63<< 7<< 0 <<14<<18<< 2<< 0; N.Row(8) << 0 << 0<< 0<< 0 <<14<<56<<35<<42 << 4<<16<<10<<12; N.Row(9) << 0 << 0<< 0<< 0 << 0<< 0<< 0<< 0 <<16<< 0<< 0<< 0; N.Row(10)<< 0 << 0<< 0<< 0 << 0<< 0<< 0<< 0 << 4<<12<< 0<< 0; N.Row(11)<< 0 << 0<< 0<< 0 << 0<< 0<< 0<< 0 <<28<<36<< 4<< 0; N.Row(12)<< 0 << 0<< 0<< 0 << 0<< 0<< 0<< 0 << 8<<32<<20<<24; Matrix N1 = KP(A, BT); N1 -= N; Print(N1); AB << KP(A, BT); AB << (AB - N); Print(AB); BT << KP(A, BT); BT << (BT - N); Print(BT); LowerTriangularMatrix AT = A.t(); N1 = KP(AT, B); N1 -= N.t(); Print(N1); AB << KP(AT, B); AB << (AB - N.t()); Print(AB); BT << KP(AT, B); BT << (BT - N.t()); Print(BT); } { Tracer et1("Stage 3"); BandMatrix BMA(6,2,3); BMA.Row(1) << 5.25 << 4.75 << 2.25 << 1.75; BMA.Row(2) << 1.25 << 9.75 << 4.50 << 0.25 << 1.50; BMA.Row(3) << 7.75 << 1.50 << 3.00 << 4.25 << 0.50 << 5.50; BMA.Row(4) << 2.75 << 9.00 << 8.00 << 3.25 << 3.50; BMA.Row(5) << 8.75 << 6.25 << 5.00 << 5.75; BMA.Row(6) << 3.75 << 6.75 << 6.00; Matrix A = BMA; BandMatrix BMB(4,2,1); BMB.Row(1) << 4.5 << 9.5; BMB.Row(2) << 1.5 << 6.0 << 2.0; BMB.Row(3) << 0.5 << 2.5 << 8.5 << 7.5; BMB.Row(4) << 3.0 << 4.0 << 6.5; Matrix B = BMB; BandMatrix BMC = KP(BMA, BMB); BandMatrix BMC1(24,11,15); BMC1.Inject(Matrix(KP(BMA, B))); // not directly Band Matrix Matrix C2 = KP(A, BMB); Matrix C = KP(A, B); Matrix M = C - BMC; Print(M); M = C - BMC1; Print(M); M = C - C2; Print(M); RowVector X(4); X(1) = BMC.BandWidth().Lower() - 10; X(2) = BMC.BandWidth().Upper() - 13; X(3) = BMC1.BandWidth().Lower() - 11; X(4) = BMC1.BandWidth().Upper() - 15; Print(X); UpperTriangularMatrix UT; UT << KP(BMA, BMB); UpperTriangularMatrix UT1; UT1 << (C - UT); Print(UT1); LowerTriangularMatrix LT; LT << KP(BMA, BMB); LowerTriangularMatrix LT1; LT1 << (C - LT); Print(LT1); } { Tracer et1("Stage 4"); SymmetricMatrix SM1(4); SM1.Row(1) << 2; SM1.Row(2) << 4 << 5; SM1.Row(3) << 9 << 2 << 1; SM1.Row(4) << 3 << 6 << 8 << 2; SymmetricMatrix SM2(3); SM2.Row(1) << 3; SM2.Row(2) << -7 << -6; SM2.Row(3) << 4 << -2 << -1; SymmetricMatrix SM = KP(SM1, SM2); Matrix M1 = SM1; Matrix M2 = SM2; Matrix M = KP(SM1, SM2); M -= SM; Print(M); M = KP(SM1, SM2) - SM; Print(M); M = KP(M1, SM2) - SM; Print(M); M = KP(SM1, M2) - SM; Print(M); M = KP(M1, M2); M -= SM; Print(M); } { Tracer et1("Stage 5"); Matrix A(2,3); A << 3 << 5 << 2 << 4 << 1 << 6; Matrix B(3,4); B << 7 << 2 << 9 << 11 << 1 << 3 << 6 << 8 << 4 << 10 << 5 << 12; RowVector C(2); C << 3 << 7; ColumnVector D(4); D << 0 << 5 << 13 << 11; Matrix M = KP(C * A, B * D) - KP(C, B) * KP(A, D); Print(M); } { Tracer et1("Stage 6"); RowVector A(3), B(5), C(15); A << 5 << 2 << 4; B << 3 << 2 << 0 << 1 << 6; C << 15 << 10 << 0 << 5 << 30 << 6 << 4 << 0 << 2 << 12 << 12 << 8 << 0 << 4 << 24; Matrix N = KP(A, B) - C; Print(N); N = KP(A.t(), B.t()) - C.t(); Print(N); N = KP(A.AsDiagonal(), B.AsDiagonal()) - C.AsDiagonal(); Print(N); } }