Matrix.cs 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace VisualMath.Accord.Math
  7. {
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Linq;
  12. using VisualMath.Accord.Math.Decompositions;
  13. using AForge;
  14. using AForge.Math;
  15. using AForge.Math.Random;
  16. /// <summary>
  17. /// Static class Matrix. Defines a set of extension methods
  18. /// that operates mainly on multidimensional arrays and vectors.
  19. /// </summary>
  20. public static class Matrix
  21. {
  22. #region Comparison and Rounding
  23. /// <summary>
  24. /// Compares two matrices for equality, considering an acceptance threshold.
  25. /// </summary>
  26. public static bool IsEqual(this double[,] a, double[,] b, double threshold)
  27. {
  28. for (int i = 0; i < a.GetLength(0); i++)
  29. {
  30. for (int j = 0; j < b.GetLength(1); j++)
  31. {
  32. double x = a[i, j], y = b[i, j];
  33. if (System.Math.Abs(x - y) > threshold || (Double.IsNaN(x) ^ Double.IsNaN(y)))
  34. return false;
  35. }
  36. }
  37. return true;
  38. }
  39. /// <summary>
  40. /// Compares two matrices for equality, considering an acceptance threshold.
  41. /// </summary>
  42. public static bool IsEqual(this float[,] a, float[,] b, float threshold)
  43. {
  44. for (int i = 0; i < a.GetLength(0); i++)
  45. {
  46. for (int j = 0; j < b.GetLength(1); j++)
  47. {
  48. float x = a[i, j], y = b[i, j];
  49. if (System.Math.Abs(x - y) > threshold || (Single.IsNaN(x) ^ Single.IsNaN(y)))
  50. return false;
  51. }
  52. }
  53. return true;
  54. }
  55. /// <summary>
  56. /// Compares two matrices for equality, considering an acceptance threshold.
  57. /// </summary>
  58. public static bool IsEqual(this double[][] a, double[][] b, double threshold)
  59. {
  60. for (int i = 0; i < a.Length; i++)
  61. {
  62. for (int j = 0; j < a[i].Length; j++)
  63. {
  64. double x = a[i][j], y = b[i][j];
  65. if (System.Math.Abs(x - y) > threshold || (Double.IsNaN(x) ^ Double.IsNaN(y)))
  66. {
  67. return false;
  68. }
  69. }
  70. }
  71. return true;
  72. }
  73. /// <summary>
  74. /// Compares two vectors for equality, considering an acceptance threshold.
  75. /// </summary>
  76. public static bool IsEqual(this double[] a, double[] b, double threshold)
  77. {
  78. for (int i = 0; i < a.Length; i++)
  79. {
  80. if (System.Math.Abs(a[i] - b[i]) > threshold)
  81. return false;
  82. }
  83. return true;
  84. }
  85. /// <summary>
  86. /// Compares each member of a vector for equality with a scalar value x.
  87. /// </summary>
  88. public static bool IsEqual(this double[] a, double x)
  89. {
  90. for (int i = 0; i < a.Length; i++)
  91. {
  92. if (a[i] != x)
  93. return false;
  94. }
  95. return true;
  96. }
  97. /// <summary>
  98. /// Compares each member of a matrix for equality with a scalar value x.
  99. /// </summary>
  100. public static bool IsEqual(this double[,] a, double x)
  101. {
  102. for (int i = 0; i < a.GetLength(0); i++)
  103. {
  104. for (int j = 0; j < a.GetLength(1); j++)
  105. {
  106. if (a[i, j] != x)
  107. return false;
  108. }
  109. }
  110. return true;
  111. }
  112. /// <summary>
  113. /// Compares two matrices for equality.
  114. /// </summary>
  115. public static bool IsEqual<T>(this T[][] a, T[][] b)
  116. {
  117. if (a.Length != b.Length)
  118. return false;
  119. for (int i = 0; i < a.Length; i++)
  120. {
  121. if (a[i] == b[i])
  122. continue;
  123. if (a[i] == null || b[i] == null)
  124. return false;
  125. if (a[i].Length != b[i].Length)
  126. return false;
  127. for (int j = 0; j < a[i].Length; j++)
  128. {
  129. if (!a[i][j].Equals(b[i][j]))
  130. return false;
  131. }
  132. }
  133. return true;
  134. }
  135. /// <summary>Compares two matrices for equality.</summary>
  136. public static bool IsEqual<T>(this T[,] a, T[,] b)
  137. {
  138. if (a.GetLength(0) != b.GetLength(0) ||
  139. a.GetLength(1) != b.GetLength(1))
  140. return false;
  141. int rows = a.GetLength(0);
  142. int cols = a.GetLength(1);
  143. for (int i = 0; i < rows; i++)
  144. {
  145. for (int j = 0; j < cols; j++)
  146. {
  147. if (!a[i, j].Equals(b[i, j]))
  148. return false;
  149. }
  150. }
  151. return true;
  152. }
  153. /// <summary>Compares two vectors for equality.</summary>
  154. public static bool IsEqual<T>(this T[] a, params T[] b)
  155. {
  156. if (a.Length != b.Length)
  157. return false;
  158. for (int i = 0; i < a.Length; i++)
  159. {
  160. if (!a[i].Equals(b[i]))
  161. return false;
  162. }
  163. return true;
  164. }
  165. /// <summary>
  166. /// This method should not be called. Use Matrix.IsEqual instead.
  167. /// </summary>
  168. public static new bool Equals(object value)
  169. {
  170. throw new NotSupportedException("Use Matrix.IsEqual instead.");
  171. }
  172. #endregion
  173. #region Matrix Algebra
  174. /// <summary>
  175. /// Gets the transpose of a matrix.
  176. /// </summary>
  177. /// <param name="value">A matrix.</param>
  178. /// <returns>The transpose of matrix m.</returns>
  179. public static T[,] Transpose<T>(this T[,] value)
  180. {
  181. int rows = value.GetLength(0);
  182. int cols = value.GetLength(1);
  183. T[,] t = new T[cols, rows];
  184. for (int i = 0; i < rows; i++)
  185. for (int j = 0; j < cols; j++)
  186. t[j, i] = value[i, j];
  187. return t;
  188. }
  189. /// <summary>
  190. /// Gets the transpose of a row vector.
  191. /// </summary>
  192. /// <param name="value">A row vector.</param>
  193. /// <returns>The transpose of the vector.</returns>
  194. public static T[,] Transpose<T>(this T[] value)
  195. {
  196. T[,] t = new T[value.Length, 1];
  197. for (int i = 0; i < value.Length; i++)
  198. t[i, 0] = value[i];
  199. return t;
  200. }
  201. #region Multiplication
  202. /// <summary>
  203. /// Multiplies two matrices.
  204. /// </summary>
  205. /// <param name="a">The left matrix.</param>
  206. /// <param name="b">The right matrix.</param>
  207. /// <returns>The product of the multiplication of the two matrices.</returns>
  208. public static double[,] Multiply(this double[,] a, double[,] b)
  209. {
  210. double[,] r = new double[a.GetLength(0), b.GetLength(1)];
  211. Multiply(a, b, r);
  212. return r;
  213. }
  214. /// <summary>
  215. /// Multiplies two matrices.
  216. /// </summary>
  217. /// <param name="a">The left matrix.</param>
  218. /// <param name="b">The right matrix.</param>
  219. /// <param name="r">The matrix to store results.</param>
  220. public static unsafe void Multiply(this double[,] a, double[,] b, double[,] r)
  221. {
  222. int n = a.GetLength(1);
  223. int m = a.GetLength(0);
  224. int p = b.GetLength(1);
  225. fixed (double* ptrA = a)
  226. {
  227. double[] Bcolj = new double[n];
  228. for (int j = 0; j < p; j++)
  229. {
  230. for (int k = 0; k < n; k++)
  231. Bcolj[k] = b[k, j];
  232. double* Arowi = ptrA;
  233. for (int i = 0; i < m; i++)
  234. {
  235. double s = 0;
  236. for (int k = 0; k < n; k++)
  237. s += *(Arowi++) * Bcolj[k];
  238. r[i, j] = s;
  239. }
  240. }
  241. }
  242. }
  243. /// <summary>
  244. /// Multiplies two matrices.
  245. /// </summary>
  246. /// <param name="a">The left matrix.</param>
  247. /// <param name="b">The right matrix.</param>
  248. /// <returns>The product of the multiplication of the two matrices.</returns>
  249. public static float[,] Multiply(this float[,] a, float[,] b)
  250. {
  251. float[,] r = new float[a.GetLength(0), b.GetLength(1)];
  252. Multiply(a, b, r);
  253. return r;
  254. }
  255. /// <summary>
  256. /// Multiplies two matrices.
  257. /// </summary>
  258. /// <param name="a">The left matrix.</param>
  259. /// <param name="b">The right matrix.</param>
  260. /// <param name="r">The matrix to store results.</param>
  261. public static unsafe void Multiply(this float[,] a, float[,] b, float[,] r)
  262. {
  263. int acols = a.GetLength(1);
  264. int arows = a.GetLength(0);
  265. int bcols = b.GetLength(1);
  266. fixed (float* ptrA = a)
  267. {
  268. float[] Bcolj = new float[acols];
  269. for (int j = 0; j < bcols; j++)
  270. {
  271. for (int k = 0; k < acols; k++)
  272. Bcolj[k] = b[k, j];
  273. float* Arowi = ptrA;
  274. for (int i = 0; i < arows; i++)
  275. {
  276. float s = 0;
  277. for (int k = 0; k < acols; k++)
  278. s += *(Arowi++) * Bcolj[k];
  279. r[i, j] = s;
  280. }
  281. }
  282. }
  283. }
  284. /// <summary>
  285. /// Multiplies a row vector and a matrix.
  286. /// </summary>
  287. /// <param name="a">A row vector.</param>
  288. /// <param name="b">A matrix.</param>
  289. /// <returns>The product of the multiplication of the row vector and the matrix.</returns>
  290. public static double[] Multiply(this double[] a, double[,] b)
  291. {
  292. if (b.GetLength(0) != a.Length)
  293. throw new ArgumentException("Matrix dimensions must match", "b");
  294. double[] r = new double[b.GetLength(1)];
  295. for (int j = 0; j < b.GetLength(1); j++)
  296. for (int k = 0; k < a.Length; k++)
  297. r[j] += a[k] * b[k, j];
  298. return r;
  299. }
  300. /// <summary>
  301. /// Multiplies a matrix and a vector (a*bT).
  302. /// </summary>
  303. /// <param name="a">A matrix.</param>
  304. /// <param name="b">A column vector.</param>
  305. /// <returns>The product of the multiplication of matrix a and column vector b.</returns>
  306. public static double[] Multiply(this double[,] a, double[] b)
  307. {
  308. if (a.GetLength(1) != b.Length)
  309. throw new ArgumentException("Matrix dimensions must match", "b");
  310. double[] r = new double[a.GetLength(0)];
  311. for (int i = 0; i < a.GetLength(0); i++)
  312. for (int j = 0; j < b.Length; j++)
  313. r[i] += a[i, j] * b[j];
  314. return r;
  315. }
  316. /// <summary>
  317. /// Multiplies a matrix by a scalar.
  318. /// </summary>
  319. /// <param name="a">A matrix.</param>
  320. /// <param name="x">A scalar.</param>
  321. /// <returns>The product of the multiplication of matrix a and scalar x.</returns>
  322. public static double[,] Multiply(this double[,] a, double x)
  323. {
  324. int rows = a.GetLength(0);
  325. int cols = a.GetLength(1);
  326. double[,] r = new double[rows, cols];
  327. for (int i = 0; i < rows; i++)
  328. for (int j = 0; j < cols; j++)
  329. r[i, j] = a[i, j] * x;
  330. return r;
  331. }
  332. /// <summary>
  333. /// Multiplies a vector by a scalar.
  334. /// </summary>
  335. /// <param name="a">A vector.</param>
  336. /// <param name="x">A scalar.</param>
  337. /// <returns>The product of the multiplication of vector a and scalar x.</returns>
  338. public static double[] Multiply(this double[] a, double x)
  339. {
  340. double[] r = new double[a.Length];
  341. for (int i = 0; i < a.Length; i++)
  342. r[i] = a[i] * x;
  343. return r;
  344. }
  345. /// <summary>
  346. /// Multiplies a matrix by a scalar.
  347. /// </summary>
  348. /// <param name="a">A scalar.</param>
  349. /// <param name="x">A matrix.</param>
  350. /// <returns>The product of the multiplication of vector a and scalar x.</returns>
  351. public static double[,] Multiply(this double x, double[,] a)
  352. {
  353. return a.Multiply(x);
  354. }
  355. /// <summary>
  356. /// Multiplies a vector by a scalar.
  357. /// </summary>
  358. /// <param name="a">A scalar.</param>
  359. /// <param name="x">A matrix.</param>
  360. /// <returns>The product of the multiplication of vector a and scalar x.</returns>
  361. public static double[] Multiply(this double x, double[] a)
  362. {
  363. return a.Multiply(x);
  364. }
  365. #endregion
  366. #region Division
  367. /// <summary>
  368. /// Divides a vector by a scalar.
  369. /// </summary>
  370. /// <param name="a">A vector.</param>
  371. /// <param name="x">A scalar.</param>
  372. /// <returns>The division quotient of vector a and scalar x.</returns>
  373. public static double[] Divide(this double[] a, double x)
  374. {
  375. double[] r = new double[a.Length];
  376. for (int i = 0; i < a.Length; i++)
  377. r[i] = a[i] / x;
  378. return r;
  379. }
  380. /// <summary>
  381. /// Divides two matrices by multiplying A by the inverse of B.
  382. /// </summary>
  383. /// <param name="a">The first matrix.</param>
  384. /// <param name="b">The second matrix (which will be inverted).</param>
  385. /// <returns>The result from the division of a and b.</returns>
  386. public static double[,] Divide(this double[,] a, double[,] b)
  387. {
  388. //return a.Multiply(b.Inverse());
  389. if (a.GetLength(0) == a.GetLength(1))
  390. {
  391. // Solve by LU Decomposition if matrix is square.
  392. return new LuDecomposition(b, true).SolveTranspose(a);
  393. }
  394. else
  395. {
  396. // Solve by QR Decomposition if not.
  397. return new QrDecomposition(b, true).SolveTranspose(a);
  398. }
  399. }
  400. /// <summary>
  401. /// Divides a matrix by a scalar.
  402. /// </summary>
  403. /// <param name="a">A matrix.</param>
  404. /// <param name="x">A scalar.</param>
  405. /// <returns>The division quotient of matrix a and scalar x.</returns>
  406. public static double[,] Divide(this double[,] a, double x)
  407. {
  408. int rows = a.GetLength(0);
  409. int cols = a.GetLength(1);
  410. double[,] r = new double[rows, cols];
  411. for (int i = 0; i < rows; i++)
  412. for (int j = 0; j < cols; j++)
  413. r[i, j] = a[i, j] / x;
  414. return r;
  415. }
  416. #endregion
  417. #region Products
  418. /// <summary>
  419. /// Gets the inner product (scalar product) between two vectors (aT*b).
  420. /// </summary>
  421. /// <param name="a">A vector.</param>
  422. /// <param name="b">A vector.</param>
  423. /// <returns>The inner product of the multiplication of the vectors.</returns>
  424. /// <remarks>
  425. /// In mathematics, the dot product is an algebraic operation that takes two
  426. /// equal-length sequences of numbers (usually coordinate vectors) and returns
  427. /// a single number obtained by multiplying corresponding entries and adding up
  428. /// those products. The name is derived from the dot that is often used to designate
  429. /// this operation; the alternative name scalar product emphasizes the scalar
  430. /// (rather than vector) nature of the result.
  431. ///
  432. /// The principal use of this product is the inner product in a Euclidean vector space:
  433. /// when two vectors are expressed on an orthonormal basis, the dot product of their
  434. /// coordinate vectors gives their inner product.
  435. /// </remarks>
  436. public static double InnerProduct(this double[] a, double[] b)
  437. {
  438. double r = 0.0;
  439. if (a.Length != b.Length)
  440. throw new ArgumentException("Vector dimensions must match", "b");
  441. for (int i = 0; i < a.Length; i++)
  442. r += a[i] * b[i];
  443. return r;
  444. }
  445. /// <summary>
  446. /// Gets the outer product (matrix product) between two vectors (a*bT).
  447. /// </summary>
  448. /// <remarks>
  449. /// In linear algebra, the outer product typically refers to the tensor
  450. /// product of two vectors. The result of applying the outer product to
  451. /// a pair of vectors is a matrix. The name contrasts with the inner product,
  452. /// which takes as input a pair of vectors and produces a scalar.
  453. /// </remarks>
  454. public static double[,] OuterProduct(this double[] a, double[] b)
  455. {
  456. double[,] r = new double[a.Length, b.Length];
  457. for (int i = 0; i < a.Length; i++)
  458. for (int j = 0; j < b.Length; j++)
  459. r[i, j] += a[i] * b[j];
  460. return r;
  461. }
  462. /// <summary>
  463. /// Vectorial product.
  464. /// </summary>
  465. /// <remarks>
  466. /// The cross product, vector product or Gibbs vector product is a binary operation
  467. /// on two vectors in three-dimensional space. It has a vector result, a vector which
  468. /// is always perpendicular to both of the vectors being multiplied and the plane
  469. /// containing them. It has many applications in mathematics, engineering and physics.
  470. /// </remarks>
  471. public static double[] VectorProduct(double[] a, double[] b)
  472. {
  473. return new double[] {
  474. a[1]*b[2] - a[2]*b[1],
  475. a[2]*b[0] - a[0]*b[2],
  476. a[0]*b[1] - a[1]*b[0]
  477. };
  478. }
  479. /// <summary>
  480. /// Vectorial product.
  481. /// </summary>
  482. public static float[] VectorProduct(float[] a, float[] b)
  483. {
  484. return new float[] {
  485. a[1]*b[2] - a[2]*b[1],
  486. a[2]*b[0] - a[0]*b[2],
  487. a[0]*b[1] - a[1]*b[0]
  488. };
  489. }
  490. /// <summary>
  491. /// Computes the cartesian product of many sets.
  492. /// </summary>
  493. /// <remarks>
  494. /// References:
  495. /// - http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
  496. /// </remarks>
  497. public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
  498. {
  499. IEnumerable<IEnumerable<T>> empty = new[] { Enumerable.Empty<T>() };
  500. return sequences.Aggregate(empty, (accumulator, sequence) =>
  501. from accumulatorSequence in accumulator
  502. from item in sequence
  503. select accumulatorSequence.Concat(new[] { item }));
  504. }
  505. /// <summary>
  506. /// Computes the cartesian product of many sets.
  507. /// </summary>
  508. public static T[][] CartesianProduct<T>(params T[][] sequences)
  509. {
  510. var result = CartesianProduct(sequences as IEnumerable<IEnumerable<T>>);
  511. List<T[]> list = new List<T[]>();
  512. foreach (IEnumerable<T> point in result)
  513. list.Add(point.ToArray());
  514. return list.ToArray();
  515. }
  516. /// <summary>
  517. /// Computes the cartesian product of two sets.
  518. /// </summary>
  519. public static T[][] CartesianProduct<T>(this T[] sequence1, T[] sequence2)
  520. {
  521. return CartesianProduct(new T[][] { sequence1, sequence2 });
  522. }
  523. #endregion
  524. #region Addition and Subraction
  525. /// <summary>
  526. /// Adds two matrices.
  527. /// </summary>
  528. /// <param name="a">A matrix.</param>
  529. /// <param name="b">A matrix.</param>
  530. /// <returns>The sum of the two matrices a and b.</returns>
  531. public static double[,] Add(this double[,] a, double[,] b)
  532. {
  533. if (a.GetLength(0) != b.GetLength(0) || a.GetLength(1) != b.GetLength(1))
  534. throw new ArgumentException("Matrix dimensions must match", "b");
  535. int rows = a.GetLength(0);
  536. int cols = b.GetLength(1);
  537. double[,] r = new double[rows, cols];
  538. for (int i = 0; i < rows; i++)
  539. for (int j = 0; j < cols; j++)
  540. r[i, j] = a[i, j] + b[i, j];
  541. return r;
  542. }
  543. /// <summary>
  544. /// Adds a vector to a column or row of a matrix.
  545. /// </summary>
  546. /// <param name="a">A matrix.</param>
  547. /// <param name="b">A vector.</param>
  548. /// <param name="dimension">
  549. /// Pass 0 if the vector should be added row-wise,
  550. /// or 1 if the vector should be added column-wise.
  551. /// </param>
  552. public static double[,] Add(this double[,] a, double[] b, int dimension)
  553. {
  554. int rows = a.GetLength(0);
  555. int cols = a.GetLength(1);
  556. double[,] r = new double[rows, cols];
  557. if (dimension == 1)
  558. {
  559. if (rows != b.Length) throw new ArgumentException(
  560. "Length of B should equal the number of rows in A", "b");
  561. for (int j = 0; j < cols; j++)
  562. for (int i = 0; i < rows; i++)
  563. r[i, j] = a[i, j] + b[i];
  564. }
  565. else
  566. {
  567. if (cols != b.Length) throw new ArgumentException(
  568. "Length of B should equal the number of cols in A", "b");
  569. for (int i = 0; i < rows; i++)
  570. for (int j = 0; j < cols; j++)
  571. r[i, j] = a[i, j] + b[j];
  572. }
  573. return r;
  574. }
  575. /// <summary>
  576. /// Adds a vector to a column or row of a matrix.
  577. /// </summary>
  578. /// <param name="a">A matrix.</param>
  579. /// <param name="b">A vector.</param>
  580. /// <param name="dimension">The dimension to add the vector to.</param>
  581. public static double[,] Subtract(this double[,] a, double[] b, int dimension)
  582. {
  583. int rows = a.GetLength(0);
  584. int cols = a.GetLength(1);
  585. double[,] r = new double[rows, cols];
  586. if (dimension == 1)
  587. {
  588. if (rows != b.Length) throw new ArgumentException(
  589. "Length of B should equal the number of rows in A", "b");
  590. for (int j = 0; j < cols; j++)
  591. for (int i = 0; i < rows; i++)
  592. r[i, j] = a[i, j] - b[i];
  593. }
  594. else
  595. {
  596. if (cols != b.Length) throw new ArgumentException(
  597. "Length of B should equal the number of cols in A", "b");
  598. for (int i = 0; i < rows; i++)
  599. for (int j = 0; j < cols; j++)
  600. r[i, j] = a[i, j] - b[j];
  601. }
  602. return r;
  603. }
  604. /// <summary>
  605. /// Adds two vectors.
  606. /// </summary>
  607. /// <param name="a">A vector.</param>
  608. /// <param name="b">A vector.</param>
  609. /// <returns>The addition of vector a to vector b.</returns>
  610. public static double[] Add(this double[] a, double[] b)
  611. {
  612. if (a.Length != b.Length)
  613. throw new ArgumentException("Vector lengths must match", "b");
  614. double[] r = new double[a.Length];
  615. for (int i = 0; i < a.Length; i++)
  616. r[i] = a[i] + b[i];
  617. return r;
  618. }
  619. /// <summary>
  620. /// Subtracts two matrices.
  621. /// </summary>
  622. /// <param name="a">A matrix.</param>
  623. /// <param name="b">A matrix.</param>
  624. /// <returns>The subtraction of matrix b from matrix a.</returns>
  625. public static double[,] Subtract(this double[,] a, double[,] b)
  626. {
  627. if (a.GetLength(0) != b.GetLength(0) || a.GetLength(1) != b.GetLength(1))
  628. throw new ArgumentException("Matrix dimensions must match", "b");
  629. int rows = a.GetLength(0);
  630. int cols = b.GetLength(1);
  631. double[,] r = new double[rows, cols];
  632. for (int i = 0; i < rows; i++)
  633. for (int j = 0; j < cols; j++)
  634. r[i, j] = a[i, j] - b[i, j];
  635. return r;
  636. }
  637. /// <summary>
  638. /// Subtracts two vectors.
  639. /// </summary>
  640. /// <param name="a">A vector.</param>
  641. /// <param name="b">A vector.</param>
  642. /// <returns>The subtraction of vector b from vector a.</returns>
  643. public static double[] Subtract(this double[] a, double[] b)
  644. {
  645. if (a.Length != b.Length)
  646. throw new ArgumentException("Vector length must match", "b");
  647. double[] r = new double[a.Length];
  648. for (int i = 0; i < a.Length; i++)
  649. r[i] = a[i] - b[i];
  650. return r;
  651. }
  652. /// <summary>
  653. /// Subtracts a scalar from a vector.
  654. /// </summary>
  655. /// <param name="a">A vector.</param>
  656. /// <param name="b">A scalar.</param>
  657. /// <returns>The subtraction of b from all elements in a.</returns>
  658. public static double[] Subtract(this double[] a, double b)
  659. {
  660. double[] r = new double[a.Length];
  661. for (int i = 0; i < a.Length; i++)
  662. r[i] = a[i] - b;
  663. return r;
  664. }
  665. #endregion
  666. /// <summary>
  667. /// Multiplies a matrix by itself n times.
  668. /// </summary>
  669. public static double[,] Power(double[,] matrix, int n)
  670. {
  671. if (!matrix.IsSquare())
  672. throw new ArgumentException("Matrix must be square", "matrix");
  673. // TODO: This is a very naive implementation and should be optimized.
  674. double[,] r = matrix;
  675. for (int i = 0; i < n; i++)
  676. r = r.Multiply(matrix);
  677. return r;
  678. }
  679. #endregion
  680. #region Matrix Construction
  681. /// <summary>
  682. /// Creates a rows-by-cols matrix with uniformly distributed random data.
  683. /// </summary>
  684. public static double[,] Random(int rows, int cols)
  685. {
  686. return Random(rows, cols, 0, 1);
  687. }
  688. /// <summary>
  689. /// Creates a rows-by-cols matrix with uniformly distributed random data.
  690. /// </summary>
  691. public static double[,] Random(int size, bool symmetric, double minValue, double maxValue)
  692. {
  693. double[,] r = new double[size, size];
  694. if (!symmetric)
  695. {
  696. for (int i = 0; i < size; i++)
  697. for (int j = 0; j < size; j++)
  698. r[i, j] = Accord.Math.Tools.Random.NextDouble() * (maxValue - minValue) + minValue;
  699. }
  700. else
  701. {
  702. for (int i = 0; i < size; i++)
  703. {
  704. for (int j = i; j < size; j++)
  705. {
  706. r[i, j] = Accord.Math.Tools.Random.NextDouble() * (maxValue - minValue) + minValue;
  707. r[j, i] = r[i, j];
  708. }
  709. }
  710. }
  711. return r;
  712. }
  713. /// <summary>
  714. /// Creates a rows-by-cols matrix with uniformly distributed random data.
  715. /// </summary>
  716. public static double[,] Random(int rows, int cols, double minValue, double maxValue)
  717. {
  718. double[,] r = new double[rows, cols];
  719. for (int i = 0; i < rows; i++)
  720. for (int j = 0; j < cols; j++)
  721. r[i, j] = Accord.Math.Tools.Random.NextDouble() * (maxValue - minValue) + minValue;
  722. return r;
  723. }
  724. /// <summary>
  725. /// Creates a rows-by-cols matrix random data drawn from a given distribution.
  726. /// </summary>
  727. public static double[,] Random(int rows, int cols, IRandomNumberGenerator generator)
  728. {
  729. double[,] r = new double[rows, cols];
  730. for (int i = 0; i < rows; i++)
  731. for (int j = 0; j < cols; j++)
  732. r[i, j] = generator.Next();
  733. return r;
  734. }
  735. /// <summary>
  736. /// Creates a vector with uniformly distributed random data.
  737. /// </summary>
  738. public static double[] Random(int size, double minValue, double maxValue)
  739. {
  740. double[] r = new double[size];
  741. for (int i = 0; i < size; i++)
  742. r[i] = Accord.Math.Tools.Random.NextDouble() * (maxValue - minValue) + minValue;
  743. return r;
  744. }
  745. /// <summary>
  746. /// Creates a vector with random data drawn from a given distribution.
  747. /// </summary>
  748. public static double[] Random(int size, IRandomNumberGenerator generator)
  749. {
  750. double[] r = new double[size];
  751. for (int i = 0; i < size; i++)
  752. r[i] = generator.Next();
  753. return r;
  754. }
  755. /// <summary>
  756. /// Creates a magic square matrix.
  757. /// </summary>
  758. public static double[,] Magic(int size)
  759. {
  760. if (size < 3)
  761. throw new ArgumentException("The square size must be greater or equal to 3.", "size");
  762. double[,] m = new double[size, size];
  763. // First algorithm: Odd order
  764. if ((size % 2) == 1)
  765. {
  766. int a = (size + 1) / 2;
  767. int b = (size + 1);
  768. for (int j = 0; j < size; j++)
  769. for (int i = 0; i < size; i++)
  770. m[i, j] = size * ((i + j + a) % size) + ((i + 2 * j + b) % size) + 1;
  771. }
  772. // Second algorithm: Even order (double)
  773. else if ((size % 4) == 0)
  774. {
  775. for (int j = 0; j < size; j++)
  776. for (int i = 0; i < size; i++)
  777. if (((i + 1) / 2) % 2 == ((j + 1) / 2) % 2)
  778. m[i, j] = size * size - size * i - j;
  779. else
  780. m[i, j] = size * i + j + 1;
  781. }
  782. // Third algorithm: Even order (single)
  783. else
  784. {
  785. int n = size / 2;
  786. int p = (size - 2) / 4;
  787. double t;
  788. var a = Matrix.Magic(n);
  789. for (int j = 0; j < n; j++)
  790. {
  791. for (int i = 0; i < n; i++)
  792. {
  793. double e = a[i, j];
  794. m[i, j] = e;
  795. m[i, j + n] = e + 2 * n * n;
  796. m[i + n, j] = e + 3 * n * n;
  797. m[i + n, j + n] = e + n * n;
  798. }
  799. }
  800. for (int i = 0; i < n; i++)
  801. {
  802. // Swap M[i,j] and M[i+n,j]
  803. for (int j = 0; j < p; j++)
  804. {
  805. t = m[i, j];
  806. m[i, j] = m[i + n, j];
  807. m[i + n, j] = t;
  808. }
  809. for (int j = size - p + 1; j < size; j++)
  810. {
  811. t = m[i, j];
  812. m[i, j] = m[i + n, j];
  813. m[i + n, j] = t;
  814. }
  815. }
  816. // Continue swaping in the boundary
  817. t = m[p, 0];
  818. m[p, 0] = m[p + n, 0];
  819. m[p + n, 0] = t;
  820. t = m[p, p];
  821. m[p, p] = m[p + n, p];
  822. m[p + n, p] = t;
  823. }
  824. return m; // return the magic square.
  825. }
  826. /// <summary>
  827. /// Gets the diagonal vector from a matrix.
  828. /// </summary>
  829. /// <param name="m">A matrix.</param>
  830. /// <returns>The diagonal vector from matrix m.</returns>
  831. public static T[] Diagonal<T>(this T[,] m)
  832. {
  833. T[] r = new T[m.GetLength(0)];
  834. for (int i = 0; i < r.Length; i++)
  835. r[i] = m[i, i];
  836. return r;
  837. }
  838. /// <summary>
  839. /// Returns a square diagonal matrix of the given size.
  840. /// </summary>
  841. public static T[,] Diagonal<T>(int size, T value)
  842. {
  843. T[,] m = new T[size, size];
  844. for (int i = 0; i < size; i++)
  845. m[i, i] = value;
  846. return m;
  847. }
  848. /// <summary>
  849. /// Returns a matrix of the given size with value on its diagonal.
  850. /// </summary>
  851. public static T[,] Diagonal<T>(int rows, int cols, T value)
  852. {
  853. T[,] m = new T[rows, cols];
  854. for (int i = 0; i < rows; i++)
  855. m[i, i] = value;
  856. return m;
  857. }
  858. /// <summary>
  859. /// Return a square matrix with a vector of values on its diagonal.
  860. /// </summary>
  861. public static T[,] Diagonal<T>(T[] values)
  862. {
  863. T[,] m = new T[values.Length, values.Length];
  864. for (int i = 0; i < values.Length; i++)
  865. m[i, i] = values[i];
  866. return m;
  867. }
  868. /// <summary>
  869. /// Return a square matrix with a vector of values on its diagonal.
  870. /// </summary>
  871. public static T[,] Diagonal<T>(int size, T[] values)
  872. {
  873. return Diagonal(size, size, values);
  874. }
  875. /// <summary>
  876. /// Returns a matrix with a vector of values on its diagonal.
  877. /// </summary>
  878. public static T[,] Diagonal<T>(int rows, int cols, T[] values)
  879. {
  880. T[,] m = new T[rows, cols];
  881. for (int i = 0; i < values.Length; i++)
  882. m[i, i] = values[i];
  883. return m;
  884. }
  885. /// <summary>
  886. /// Returns a matrix with all elements set to a given value.
  887. /// </summary>
  888. public static T[,] Create<T>(int rows, int cols, T value)
  889. {
  890. T[,] m = new T[rows, cols];
  891. for (int i = 0; i < rows; i++)
  892. for (int j = 0; j < cols; j++)
  893. m[i, j] = value;
  894. return m;
  895. }
  896. /// <summary>
  897. /// Returns a matrix with all elements set to a given value.
  898. /// </summary>
  899. public static T[,] Create<T>(int size, T value)
  900. {
  901. return Create(size, size, value);
  902. }
  903. /// <summary>
  904. /// Expands a data vector given in summary form.
  905. /// </summary>
  906. /// <param name="data">A base vector.</param>
  907. /// <param name="count">An array containing by how much each line should be replicated.</param>
  908. /// <returns></returns>
  909. public static T[] Expand<T>(T[] data, int[] count)
  910. {
  911. var expansion = new List<T>();
  912. for (int i = 0; i < count.Length; i++)
  913. for (int j = 0; j < count[i]; j++)
  914. expansion.Add(data[i]);
  915. return expansion.ToArray();
  916. }
  917. /// <summary>
  918. /// Expands a data matrix given in summary form.
  919. /// </summary>
  920. /// <param name="data">A base matrix.</param>
  921. /// <param name="count">An array containing by how much each line should be replicated.</param>
  922. /// <returns></returns>
  923. public static T[][] Expand<T>(T[][] data, int[] count)
  924. {
  925. var expansion = new List<T[]>();
  926. for (int i = 0; i < count.Length; i++)
  927. for (int j = 0; j < count[i]; j++)
  928. expansion.Add(data[i]);
  929. return expansion.ToArray();
  930. }
  931. /// <summary>
  932. /// Expands a data matrix given in summary form.
  933. /// </summary>
  934. /// <param name="data">A base matrix.</param>
  935. /// <param name="count">An array containing by how much each line should be replicated.</param>
  936. /// <returns></returns>
  937. public static T[,] Expand<T>(T[,] data, int[] count)
  938. {
  939. var expansion = new List<T[]>();
  940. for (int i = 0; i < count.Length; i++)
  941. for (int j = 0; j < count[i]; j++)
  942. expansion.Add(data.GetRow(i));
  943. return expansion.ToArray().ToMatrix();
  944. }
  945. /// <summary>
  946. /// Returns the Identity matrix of the given size.
  947. /// </summary>
  948. public static double[,] Identity(int size)
  949. {
  950. return Diagonal(size, 1.0);
  951. }
  952. /// <summary>
  953. /// Creates a centering matrix of size n x n in the form (I - 1n)
  954. /// where 1n is a matrix with all entries 1/n.
  955. /// </summary>
  956. public static double[,] Centering(int size)
  957. {
  958. double[,] r = Matrix.Create(size, -1.0 / size);
  959. for (int i = 0; i < size; i++)
  960. r[i, i] = 1.0 - 1.0 / size;
  961. return r;
  962. }
  963. /// <summary>
  964. /// Creates a matrix with a single row vector.
  965. /// </summary>
  966. public static T[,] RowVector<T>(params T[] values)
  967. {
  968. T[,] r = new T[1, values.Length];
  969. for (int i = 0; i < values.Length; i++)
  970. r[0, i] = values[i];
  971. return r;
  972. }
  973. /// <summary>
  974. /// Creates a matrix with a single column vector.
  975. /// </summary>
  976. public static T[,] ColumnVector<T>(T[] values)
  977. {
  978. T[,] r = new T[values.Length, 1];
  979. for (int i = 0; i < values.Length; i++)
  980. r[i, 0] = values[i];
  981. return r;
  982. }
  983. /// <summary>
  984. /// Creates a index vector.
  985. /// </summary>
  986. public static int[] Indexes(int from, int to)
  987. {
  988. int[] r = new int[to - from];
  989. for (int i = 0; i < r.Length; i++)
  990. r[i] = from++;
  991. return r;
  992. }
  993. /// <summary>
  994. /// Creates an interval vector.
  995. /// </summary>
  996. public static int[] Interval(int from, int to)
  997. {
  998. int[] r = new int[to - from + 1];
  999. for (int i = 0; i < r.Length; i++)
  1000. r[i] = from++;
  1001. return r;
  1002. }
  1003. /// <summary>
  1004. /// Creates an interval vector.
  1005. /// </summary>
  1006. public static double[] Interval(double from, double to, double stepSize)
  1007. {
  1008. double range = to - from;
  1009. int steps = (int)Math.Ceiling(range / stepSize) + 1;
  1010. double[] r = new double[steps];
  1011. for (int i = 0; i < r.Length; i++)
  1012. r[i] = from + i * stepSize;
  1013. return r;
  1014. }
  1015. /// <summary>
  1016. /// Creates an interval vector.
  1017. /// </summary>
  1018. public static double[] Interval(double from, double to, int steps)
  1019. {
  1020. double range = to - from;
  1021. double stepSize = range / steps;
  1022. double[] r = new double[steps + 1];
  1023. for (int i = 0; i < r.Length; i++)
  1024. r[i] = i * stepSize;
  1025. return r;
  1026. }
  1027. /// <summary>
  1028. /// Combines two vectors horizontally.
  1029. /// </summary>
  1030. public static T[] Combine<T>(this T[] a1, T[] a2)
  1031. {
  1032. T[] r = new T[a1.Length + a2.Length];
  1033. for (int i = 0; i < a1.Length; i++)
  1034. r[i] = a1[i];
  1035. for (int i = 0; i < a2.Length; i++)
  1036. r[i + a1.Length] = a2[i];
  1037. return r;
  1038. }
  1039. /// <summary>
  1040. /// Combines a vector and a element horizontally.
  1041. /// </summary>
  1042. public static T[] Combine<T>(this T[] a1, T a2)
  1043. {
  1044. T[] r = new T[a1.Length + 1];
  1045. for (int i = 0; i < a1.Length; i++)
  1046. r[i] = a1[i];
  1047. r[a1.Length] = a2;
  1048. return r;
  1049. }
  1050. /// <summary>
  1051. /// Combine vectors horizontally.
  1052. /// </summary>
  1053. public static T[] Combine<T>(params T[][] vectors)
  1054. {
  1055. int size = 0;
  1056. for (int i = 0; i < vectors.Length; i++)
  1057. size += vectors[i].Length;
  1058. T[] r = new T[size];
  1059. int c = 0;
  1060. for (int i = 0; i < vectors.Length; i++)
  1061. for (int j = 0; j < vectors[i].Length; j++)
  1062. r[c++] = vectors[i][j];
  1063. return r;
  1064. }
  1065. /// <summary>
  1066. /// Combines matrices vertically.
  1067. /// </summary>
  1068. public static T[,] Combine<T>(params T[][,] matrices)
  1069. {
  1070. int rows = 0;
  1071. int cols = 0;
  1072. for (int i = 0; i < matrices.Length; i++)
  1073. {
  1074. rows += matrices[i].GetLength(0);
  1075. if (matrices[i].GetLength(1) > cols)
  1076. cols = matrices[i].GetLength(1);
  1077. }
  1078. T[,] r = new T[rows, cols];
  1079. int c = 0;
  1080. for (int i = 0; i < matrices.Length; i++)
  1081. {
  1082. for (int j = 0; j < matrices[i].GetLength(0); j++)
  1083. {
  1084. for (int k = 0; k < matrices[i].GetLength(1); k++)
  1085. r[c, k] = matrices[i][j, k];
  1086. c++;
  1087. }
  1088. }
  1089. return r;
  1090. }
  1091. /// <summary>
  1092. /// Combines matrices vertically.
  1093. /// </summary>
  1094. public static T[][] Combine<T>(params T[][][] matrices)
  1095. {
  1096. int rows = 0;
  1097. int cols = 0;
  1098. for (int i = 0; i < matrices.Length; i++)
  1099. {
  1100. rows += matrices[i].Length;
  1101. if (matrices[i][0].Length > cols)
  1102. cols = matrices[i][0].Length;
  1103. }
  1104. T[][] r = new T[rows][];
  1105. for (int i = 0; i < rows; i++)
  1106. r[i] = new T[cols];
  1107. int c = 0;
  1108. for (int i = 0; i < matrices.Length; i++)
  1109. {
  1110. for (int j = 0; j < matrices[i].Length; j++)
  1111. {
  1112. for (int k = 0; k < matrices[i][0].Length; k++)
  1113. r[c][k] = matrices[i][j][k];
  1114. c++;
  1115. }
  1116. }
  1117. return r;
  1118. }
  1119. #endregion
  1120. #region Subsection and elements selection
  1121. /// <summary>Returns a sub matrix extracted from the current matrix.</summary>
  1122. /// <param name="data">The matrix to return the submatrix from.</param>
  1123. /// <param name="startRow">Start row index</param>
  1124. /// <param name="endRow">End row index</param>
  1125. /// <param name="startColumn">Start column index</param>
  1126. /// <param name="endColumn">End column index</param>
  1127. /// <remarks>
  1128. /// Routine adapted from Lutz Roeder's Mapack for .NET, September 2000.
  1129. /// </remarks>
  1130. public static T[,] Submatrix<T>(this T[,] data, int startRow, int endRow, int startColumn, int endColumn)
  1131. {
  1132. int rows = data.GetLength(0);
  1133. int cols = data.GetLength(1);
  1134. if ((startRow > endRow) || (startColumn > endColumn) || (startRow < 0) ||
  1135. (startRow >= rows) || (endRow < 0) || (endRow >= rows) ||
  1136. (startColumn < 0) || (startColumn >= cols) || (endColumn < 0) ||
  1137. (endColumn >= cols))
  1138. {
  1139. throw new ArgumentException("Argument out of range.");
  1140. }
  1141. T[,] X = new T[endRow - startRow + 1, endColumn - startColumn + 1];
  1142. for (int i = startRow; i <= endRow; i++)
  1143. {
  1144. for (int j = startColumn; j <= endColumn; j++)
  1145. {
  1146. X[i - startRow, j - startColumn] = data[i, j];
  1147. }
  1148. }
  1149. return X;
  1150. }
  1151. /// <summary>Returns a sub matrix extracted from the current matrix.</summary>
  1152. /// <param name="data">The matrix to return the submatrix from.</param>
  1153. /// <param name="rowIndexes">Array of row indices. Pass null to select all indices.</param>
  1154. /// <param name="columnIndexes">Array of column indices. Pass null to select all indices.</param>
  1155. /// <remarks>
  1156. /// Routine adapted from Lutz Roeder's Mapack for .NET, September 2000.
  1157. /// </remarks>
  1158. public static T[,] Submatrix<T>(this T[,] data, int[] rowIndexes, int[] columnIndexes)
  1159. {
  1160. if (rowIndexes == null)
  1161. rowIndexes = Indexes(0, data.GetLength(0));
  1162. if (columnIndexes == null)
  1163. columnIndexes = Indexes(0, data.GetLength(1));
  1164. T[,] X = new T[rowIndexes.Length, columnIndexes.Length];
  1165. for (int i = 0; i < rowIndexes.Length; i++)
  1166. {
  1167. for (int j = 0; j < columnIndexes.Length; j++)
  1168. {
  1169. if ((rowIndexes[i] < 0) || (rowIndexes[i] >= data.GetLength(0)) ||
  1170. (columnIndexes[j] < 0) || (columnIndexes[j] >= data.GetLength(1)))
  1171. {
  1172. throw new ArgumentException("Argument out of range.");
  1173. }
  1174. X[i, j] = data[rowIndexes[i], columnIndexes[j]];
  1175. }
  1176. }
  1177. return X;
  1178. }
  1179. /// <summary>Returns a sub matrix extracted from the current matrix.</summary>
  1180. /// <param name="data">The matrix to return the submatrix from.</param>
  1181. /// <param name="rowIndexes">Array of row indices</param>
  1182. /// <remarks>
  1183. /// Routine adapted from Lutz Roeder's Mapack for .NET, September 2000.
  1184. /// </remarks>
  1185. public static T[,] Submatrix<T>(this T[,] data, int[] rowIndexes)
  1186. {
  1187. T[,] X = new T[rowIndexes.Length, data.GetLength(1)];
  1188. for (int i = 0; i < rowIndexes.Length; i++)
  1189. {
  1190. for (int j = 0; j < data.GetLength(1); j++)
  1191. {
  1192. if ((rowIndexes[i] < 0) || (rowIndexes[i] >= data.GetLength(0)))
  1193. {
  1194. throw new ArgumentException("Argument out of range.");
  1195. }
  1196. X[i, j] = data[rowIndexes[i], j];
  1197. }
  1198. }
  1199. return X;
  1200. }
  1201. /// <summary>Returns a subvector extracted from the current vector.</summary>
  1202. /// <param name="data">The vector to return the subvector from.</param>
  1203. /// <param name="indexes">Array of indices.</param>
  1204. /// <remarks>
  1205. /// Routine adapted from Lutz Roeder's Mapack for .NET, September 2000.
  1206. /// </remarks>
  1207. public static T[] Submatrix<T>(this T[] data, int[] indexes)
  1208. {
  1209. T[] X = new T[indexes.Length];
  1210. for (int i = 0; i < indexes.Length; i++)
  1211. {
  1212. X[i] = data[indexes[i]];
  1213. }
  1214. return X;
  1215. }
  1216. /// <summary>Returns a sub matrix extracted from the current matrix.</summary>
  1217. /// <param name="data">The vector to return the subvector from.</param>
  1218. /// <param name="i0">Starting index.</param>
  1219. /// <param name="i1">End index.</param>
  1220. /// <remarks>
  1221. /// Routine adapted from Lutz Roeder's Mapack for .NET, September 2000.
  1222. /// </remarks>
  1223. public static T[] Submatrix<T>(this T[] data, int i0, int i1)
  1224. {
  1225. T[] X = new T[i1 - i0 + 1];
  1226. for (int i = i0; i <= i1; i++)
  1227. {
  1228. X[i - i0] = data[i];
  1229. }
  1230. return X;
  1231. }
  1232. /// <summary>Returns a sub matrix extracted from the current matrix.</summary>
  1233. /// <remarks>
  1234. /// Routine adapted from Lutz Roeder's Mapack for .NET, September 2000.
  1235. /// </remarks>
  1236. public static T[] Submatrix<T>(this T[] data, int first)
  1237. {
  1238. if (first < 1 || first > data.Length)
  1239. throw new ArgumentOutOfRangeException("first");
  1240. return Submatrix<T>(data, 0, first - 1);
  1241. }
  1242. /// <summary>Returns a sub matrix extracted from the current matrix.</summary>
  1243. /// <param name="data">The matrix to return the submatrix from.</param>
  1244. /// <param name="i0">Starting row index</param>
  1245. /// <param name="i1">End row index</param>
  1246. /// <param name="c">Array of column indices</param>
  1247. /// <remarks>
  1248. /// Routine adapted from Lutz Roeder's Mapack for .NET, September 2000.
  1249. /// </remarks>
  1250. public static T[,] Submatrix<T>(this T[,] data, int i0, int i1, int[] c)
  1251. {
  1252. if ((i0 > i1) || (i0 < 0) || (i0 >= data.GetLength(0))
  1253. || (i1 < 0) || (i1 >= data.GetLength(0)))
  1254. {
  1255. throw new ArgumentException("Argument out of range.");
  1256. }
  1257. T[,] X = new T[i1 - i0 + 1, c.Length];
  1258. for (int i = i0; i <= i1; i++)
  1259. {
  1260. for (int j = 0; j < c.Length; j++)
  1261. {
  1262. if ((c[j] < 0) || (c[j] >= data.GetLength(1)))
  1263. {
  1264. throw new ArgumentException("Argument out of range.");
  1265. }
  1266. X[i - i0, j] = data[i, c[j]];
  1267. }
  1268. }
  1269. return X;
  1270. }
  1271. /// <summary>Returns a sub matrix extracted from the current matrix.</summary>
  1272. /// <param name="data">The matrix to return the submatrix from.</param>
  1273. /// <param name="r">Array of row indices</param>
  1274. /// <param name="j0">Start column index</param>
  1275. /// <param name="j1">End column index</param>
  1276. /// <remarks>
  1277. /// Routine adapted from Lutz Roeder's Mapack for .NET, September 2000.
  1278. /// </remarks>
  1279. public static T[,] Submatrix<T>(this T[,] data, int[] r, int j0, int j1)
  1280. {
  1281. if ((j0 > j1) || (j0 < 0) || (j0 >= data.GetLength(1)) || (j1 < 0)
  1282. || (j1 >= data.GetLength(1)))
  1283. {
  1284. throw new ArgumentException("Argument out of range.");
  1285. }
  1286. T[,] X = new T[r.Length, j1 - j0 + 1];
  1287. for (int i = 0; i < r.Length; i++)
  1288. {
  1289. for (int j = j0; j <= j1; j++)
  1290. {
  1291. if ((r[i] < 0) || (r[i] >= data.GetLength(0)))
  1292. {
  1293. throw new ArgumentException("Argument out of range.");
  1294. }
  1295. X[i, j - j0] = data[r[i], j];
  1296. }
  1297. }
  1298. return X;
  1299. }
  1300. /// <summary>Returns a sub matrix extracted from the current matrix.</summary>
  1301. /// <param name="data">The matrix to return the submatrix from.</param>
  1302. /// <param name="i0">Starting row index</param>
  1303. /// <param name="i1">End row index</param>
  1304. /// <param name="c">Array of column indices</param>
  1305. /// <remarks>
  1306. /// Routine adapted from Lutz Roeder's Mapack for .NET, September 2000.
  1307. /// </remarks>
  1308. public static T[][] Submatrix<T>(this T[][] data, int i0, int i1, int[] c)
  1309. {
  1310. if ((i0 > i1) || (i0 < 0) || (i0 >= data.Length)
  1311. || (i1 < 0) || (i1 >= data.Length))
  1312. {
  1313. throw new ArgumentException("Argument out of range");
  1314. }
  1315. T[][] X = new T[i1 - i0 + 1][];
  1316. for (int i = i0; i <= i1; i++)
  1317. {
  1318. X[i] = new T[c.Length];
  1319. for (int j = 0; j < c.Length; j++)
  1320. {
  1321. if ((c[j] < 0) || (c[j] >= data[i].Length))
  1322. {
  1323. throw new ArgumentException("Argument out of range.");
  1324. }
  1325. X[i - i0][j] = data[i][c[j]];
  1326. }
  1327. }
  1328. return X;
  1329. }
  1330. /// <summary>
  1331. /// Returns a new matrix without one of its columns.
  1332. /// </summary>
  1333. public static T[][] RemoveColumn<T>(this T[][] m, int index)
  1334. {
  1335. T[][] X = new T[m.Length][];
  1336. for (int i = 0; i < m.Length; i++)
  1337. {
  1338. X[i] = new T[m[i].Length - 1];
  1339. for (int j = 0; j < index; j++)
  1340. {
  1341. X[i][j] = m[i][j];
  1342. }
  1343. for (int j = index + 1; j < m[i].Length; j++)
  1344. {
  1345. X[i][j - 1] = m[i][j];
  1346. }
  1347. }
  1348. return X;
  1349. }
  1350. /// <summary>
  1351. /// Returns a new matrix with a given column vector inserted at a given index.
  1352. /// </summary>
  1353. public static T[,] InsertColumn<T>(this T[,] m, T[] column, int index)
  1354. {
  1355. int rows = m.GetLength(0);
  1356. int cols = m.GetLength(1);
  1357. T[,] X = new T[rows, cols + 1];
  1358. for (int i = 0; i < rows; i++)
  1359. {
  1360. // Copy original matrix
  1361. for (int j = 0; j < index; j++)
  1362. {
  1363. X[i, j] = m[i, j];
  1364. }
  1365. for (int j = index; j < cols; j++)
  1366. {
  1367. X[i, j + 1] = m[i, j];
  1368. }
  1369. // Copy additional column
  1370. X[i, index] = column[i];
  1371. }
  1372. return X;
  1373. }
  1374. /// <summary>
  1375. /// Removes an element from a vector.
  1376. /// </summary>
  1377. public static T[] RemoveAt<T>(this T[] array, int index)
  1378. {
  1379. T[] r = new T[array.Length - 1];
  1380. for (int i = 0; i < index; i++)
  1381. r[i] = array[i];
  1382. for (int i = index; i < r.Length; i++)
  1383. r[i] = array[i + 1];
  1384. return r;
  1385. }
  1386. /// <summary>
  1387. /// Gets a column vector from a matrix.
  1388. /// </summary>
  1389. public static T[] GetColumn<T>(this T[,] m, int index)
  1390. {
  1391. T[] column = new T[m.GetLength(0)];
  1392. for (int i = 0; i < column.Length; i++)
  1393. column[i] = m[i, index];
  1394. return column;
  1395. }
  1396. /// <summary>
  1397. /// Gets a column vector from a matrix.
  1398. /// </summary>
  1399. public static T[] GetColumn<T>(this T[][] m, int index)
  1400. {
  1401. T[] column = new T[m.Length];
  1402. for (int i = 0; i < column.Length; i++)
  1403. column[i] = m[i][index];
  1404. return column;
  1405. }
  1406. /// <summary>
  1407. /// Stores a column vector into the given column position of the matrix.
  1408. /// </summary>
  1409. public static T[,] SetColumn<T>(this T[,] m, int index, T[] column)
  1410. {
  1411. for (int i = 0; i < column.Length; i++)
  1412. m[i, index] = column[i];
  1413. return m;
  1414. }
  1415. /// <summary>
  1416. /// Gets a row vector from a matrix.
  1417. /// </summary>
  1418. public static T[] GetRow<T>(this T[,] m, int index)
  1419. {
  1420. T[] row = new T[m.GetLength(1)];
  1421. for (int i = 0; i < row.Length; i++)
  1422. row[i] = m[index, i];
  1423. return row;
  1424. }
  1425. /// <summary>
  1426. /// Stores a row vector into the given row position of the matrix.
  1427. /// </summary>
  1428. public static T[,] SetRow<T>(this T[,] m, int index, T[] row)
  1429. {
  1430. for (int i = 0; i < row.Length; i++)
  1431. m[index, i] = row[i];
  1432. return m;
  1433. }
  1434. /// <summary>
  1435. /// Gets the indices of all elements matching a certain criteria.
  1436. /// </summary>
  1437. /// <typeparam name="T">The type of the array.</typeparam>
  1438. /// <param name="data">The array to search inside.</param>
  1439. /// <param name="func">The search criteria.</param>
  1440. public static int[] Find<T>(this T[] data, Func<T, bool> func)
  1441. {
  1442. return Find(data, func, false);
  1443. }
  1444. /// <summary>
  1445. /// Gets the indices of all elements matching a certain criteria.
  1446. /// </summary>
  1447. /// <typeparam name="T">The type of the array.</typeparam>
  1448. /// <param name="data">The array to search inside.</param>
  1449. /// <param name="func">The search criteria.</param>
  1450. /// <param name="firstOnly">
  1451. /// Set to true to stop when the first element is
  1452. /// found, set to false to get all elements.
  1453. /// </param>
  1454. public static int[] Find<T>(this T[] data, Func<T, bool> func, bool firstOnly)
  1455. {
  1456. List<int> idx = new List<int>();
  1457. for (int i = 0; i < data.Length; i++)
  1458. {
  1459. if (func(data[i]))
  1460. {
  1461. if (firstOnly)
  1462. return new int[] { i };
  1463. else idx.Add(i);
  1464. }
  1465. }
  1466. return idx.ToArray();
  1467. }
  1468. /// <summary>
  1469. /// Gets the indices of all elements matching a certain criteria.
  1470. /// </summary>
  1471. /// <typeparam name="T">The type of the array.</typeparam>
  1472. /// <param name="data">The array to search inside.</param>
  1473. /// <param name="func">The search criteria.</param>
  1474. public static int[][] Find<T>(this T[,] data, Func<T, bool> func)
  1475. {
  1476. return Find(data, func, false);
  1477. }
  1478. /// <summary>
  1479. /// Gets the indices of all elements matching a certain criteria.
  1480. /// </summary>
  1481. /// <typeparam name="T">The type of the array.</typeparam>
  1482. /// <param name="data">The array to search inside.</param>
  1483. /// <param name="func">The search criteria.</param>
  1484. /// <param name="firstOnly">
  1485. /// Set to true to stop when the first element is
  1486. /// found, set to false to get all elements.
  1487. /// </param>
  1488. public static int[][] Find<T>(this T[,] data, Func<T, bool> func, bool firstOnly)
  1489. {
  1490. List<int[]> idx = new List<int[]>();
  1491. for (int i = 0; i < data.GetLength(0); i++)
  1492. {
  1493. for (int j = 0; j < data.GetLength(1); j++)
  1494. {
  1495. if (func(data[i, j]))
  1496. {
  1497. if (firstOnly)
  1498. return new int[][] { new int[] { i, j } };
  1499. else idx.Add(new int[] { i, j });
  1500. }
  1501. }
  1502. }
  1503. return idx.ToArray();
  1504. }
  1505. /// <summary>
  1506. /// Applies a function to every element of the array.
  1507. /// </summary>
  1508. public static TResult[] Apply<TData, TResult>(this TData[] data, Func<TData, TResult> func)
  1509. {
  1510. var r = new TResult[data.Length];
  1511. for (int i = 0; i < data.Length; i++)
  1512. r[i] = func(data[i]);
  1513. return r;
  1514. }
  1515. /// <summary>
  1516. /// Applies a function to every element of a matrix.
  1517. /// </summary>
  1518. public static TResult[,] Apply<TData, TResult>(this TData[,] data, Func<TData, TResult> func)
  1519. {
  1520. int rows = data.GetLength(0);
  1521. int cols = data.GetLength(1);
  1522. var r = new TResult[rows, cols];
  1523. for (int i = 0; i < rows; i++)
  1524. for (int j = 0; j < cols; j++)
  1525. r[i, j] = func(data[i, j]);
  1526. return r;
  1527. }
  1528. /// <summary>
  1529. /// Applies a function to every element of the array.
  1530. /// </summary>
  1531. public static void ApplyInPlace<TData>(this TData[] data, Func<TData, TData> func)
  1532. {
  1533. for (int i = 0; i < data.Length; i++)
  1534. data[i] = func(data[i]);
  1535. }
  1536. /// <summary>
  1537. /// Applies a function to every element of the array.
  1538. /// </summary>
  1539. public static void ApplyInPlace<TData>(this TData[] data, Func<TData, int, TData> func)
  1540. {
  1541. for (int i = 0; i < data.Length; i++)
  1542. data[i] = func(data[i], i);
  1543. }
  1544. /// <summary>
  1545. /// Sorts the columns of a matrix by sorting keys.
  1546. /// </summary>
  1547. /// <param name="keys">The key value for each column.</param>
  1548. /// <param name="values">The matrix to be sorted.</param>
  1549. /// <param name="comparer">The comparer to use.</param>
  1550. public static TValue[,] Sort<TKey, TValue>(TKey[] keys, TValue[,] values, IComparer<TKey> comparer)
  1551. {
  1552. int[] indices = new int[keys.Length];
  1553. for (int i = 0; i < keys.Length; i++) indices[i] = i;
  1554. Array.Sort<TKey, int>(keys, indices, comparer);
  1555. return values.Submatrix(0, values.GetLength(0) - 1, indices);
  1556. }
  1557. /// <summary>
  1558. /// Splits a given vector into a smaller vectors of the given size.
  1559. /// </summary>
  1560. /// <param name="vector">The vector to be splitted.</param>
  1561. /// <param name="size">The size of the resulting vectors.</param>
  1562. /// <returns>An array of vectors containing the subdivisions of the given vector.</returns>
  1563. public static T[][] Split<T>(this T[] vector, int size)
  1564. {
  1565. int n = vector.Length / size;
  1566. T[][] r = new T[n][];
  1567. for (int i = 0; i < n; i++)
  1568. {
  1569. T[] ri = r[i] = new T[size];
  1570. for (int j = 0; j < size; j++)
  1571. ri[j] = vector[j * n + i];
  1572. }
  1573. return r;
  1574. }
  1575. #endregion
  1576. #region Matrix Characteristics
  1577. /// <summary>
  1578. /// Returns true if a matrix is square.
  1579. /// </summary>
  1580. public static bool IsSquare<T>(this T[,] matrix)
  1581. {
  1582. return matrix.GetLength(0) == matrix.GetLength(1);
  1583. }
  1584. /// <summary>
  1585. /// Returns true if a matrix is symmetric.
  1586. /// </summary>
  1587. /// <param name="matrix"></param>
  1588. /// <returns></returns>
  1589. public static bool IsSymmetric(this double[,] matrix)
  1590. {
  1591. if (matrix.GetLength(0) == matrix.GetLength(1))
  1592. {
  1593. for (int i = 0; i < matrix.GetLength(0); i++)
  1594. {
  1595. for (int j = 0; j <= i; j++)
  1596. {
  1597. if (matrix[i, j] != matrix[j, i])
  1598. return false;
  1599. }
  1600. }
  1601. return true;
  1602. }
  1603. return false;
  1604. }
  1605. /// <summary>
  1606. /// Gets the trace of a matrix.
  1607. /// </summary>
  1608. /// <remarks>
  1609. /// The trace of an n-by-n square matrix A is defined to be the sum of the
  1610. /// elements on the main diagonal (the diagonal from the upper left to the
  1611. /// lower right) of A.
  1612. /// </remarks>
  1613. public static double Trace(this double[,] m)
  1614. {
  1615. double trace = 0.0;
  1616. for (int i = 0; i < m.GetLength(0); i++)
  1617. trace += m[i, i];
  1618. return trace;
  1619. }
  1620. /// <summary>
  1621. /// Gets the determinant of a matrix.
  1622. /// </summary>
  1623. public static double Determinant(this double[,] m)
  1624. {
  1625. return new LuDecomposition(m).Determinant;
  1626. }
  1627. /// <summary>
  1628. /// Gets whether a matrix is positive definite.
  1629. /// </summary>
  1630. public static bool IsPositiveDefinite(this double[,] m)
  1631. {
  1632. return new CholeskyDecomposition(m).PositiveDefinite;
  1633. }
  1634. /// <summary>Calculates a vector cumulative sum.</summary>
  1635. public static double[] CumulativeSum(this double[] value)
  1636. {
  1637. double[] sum = new double[value.Length];
  1638. sum[0] = value[0];
  1639. for (int i = 1; i < value.Length; i++)
  1640. sum[i] += sum[i - 1] + value[i];
  1641. return sum;
  1642. }
  1643. /// <summary>Calculates the matrix Sum vector.</summary>
  1644. /// <param name="value">A matrix whose sums will be calculated.</param>
  1645. /// <param name="dimension">The dimension in which the cumulative sum will be calculated.</param>
  1646. /// <returns>Returns a vector containing the sums of each variable in the given matrix.</returns>
  1647. public static double[][] CumulativeSum(this double[,] value, int dimension)
  1648. {
  1649. double[][] sum;
  1650. if (dimension == 1)
  1651. {
  1652. sum = new double[value.GetLength(0)][];
  1653. sum[0] = value.GetRow(0);
  1654. // for each row
  1655. for (int i = 1; i < value.GetLength(0); i++)
  1656. {
  1657. sum[i] = new double[value.GetLength(1)];
  1658. // for each column
  1659. for (int j = 0; j < value.GetLength(1); j++)
  1660. sum[i][j] += sum[i - 1][j] + value[i, j];
  1661. }
  1662. }
  1663. else if (dimension == 0)
  1664. {
  1665. sum = new double[value.GetLength(1)][];
  1666. sum[0] = value.GetColumn(0);
  1667. // for each column
  1668. for (int i = 1; i < value.GetLength(1); i++)
  1669. {
  1670. sum[i] = new double[value.GetLength(0)];
  1671. // for each row
  1672. for (int j = 0; j < value.GetLength(0); j++)
  1673. sum[i][j] += sum[i - 1][j] + value[j, i];
  1674. }
  1675. }
  1676. else
  1677. {
  1678. throw new ArgumentException("Invalid dimension", "dimension");
  1679. }
  1680. return sum;
  1681. }
  1682. /// <summary>Calculates the matrix Sum vector.</summary>
  1683. /// <param name="value">A matrix whose sums will be calculated.</param>
  1684. /// <returns>Returns a vector containing the sums of each variable in the given matrix.</returns>
  1685. public static double[] Sum(this double[,] value)
  1686. {
  1687. return Sum(value, 0);
  1688. }
  1689. /// <summary>Calculates the matrix Sum vector.</summary>
  1690. /// <param name="value">A matrix whose sums will be calculated.</param>
  1691. /// <param name="dimension">The dimension in which the sum will be calculated.</param>
  1692. /// <returns>Returns a vector containing the sums of each variable in the given matrix.</returns>
  1693. public static double[] Sum(this double[,] value, int dimension)
  1694. {
  1695. int rows = value.GetLength(0);
  1696. int cols = value.GetLength(1);
  1697. double[] sum;
  1698. if (dimension == 0)
  1699. {
  1700. sum = new double[cols];
  1701. for (int j = 0; j < cols; j++)
  1702. {
  1703. double s = 0.0;
  1704. for (int i = 0; i < rows; i++)
  1705. s += value[i, j];
  1706. sum[j] = s;
  1707. }
  1708. }
  1709. else if (dimension == 1)
  1710. {
  1711. sum = new double[rows];
  1712. for (int j = 0; j < rows; j++)
  1713. {
  1714. double s = 0.0;
  1715. for (int i = 0; i < cols; i++)
  1716. s += value[j, i];
  1717. sum[j] = s;
  1718. }
  1719. }
  1720. else
  1721. {
  1722. throw new ArgumentException("Invalid dimension", "dimension");
  1723. }
  1724. return sum;
  1725. }
  1726. /// <summary>Calculates the matrix Sum vector.</summary>
  1727. /// <param name="value">A matrix whose sums will be calculated.</param>
  1728. /// <returns>Returns a vector containing the sums of each variable in the given matrix.</returns>
  1729. public static int[] Sum(int[,] value)
  1730. {
  1731. return Sum(value, 0);
  1732. }
  1733. /// <summary>Calculates the matrix Sum vector.</summary>
  1734. /// <param name="value">A matrix whose sums will be calculated.</param>
  1735. /// <param name="dimension">The dimension in which the sum will be calculated.</param>
  1736. /// <returns>Returns a vector containing the sums of each variable in the given matrix.</returns>
  1737. public static int[] Sum(this int[,] value, int dimension)
  1738. {
  1739. int rows = value.GetLength(0);
  1740. int cols = value.GetLength(1);
  1741. int[] sum;
  1742. if (dimension == 0)
  1743. {
  1744. sum = new int[cols];
  1745. for (int j = 0; j < cols; j++)
  1746. {
  1747. int s = 0;
  1748. for (int i = 0; i < rows; i++)
  1749. s += value[i, j];
  1750. sum[j] = s;
  1751. }
  1752. }
  1753. else if (dimension == 1)
  1754. {
  1755. sum = new int[rows];
  1756. for (int j = 0; j < rows; j++)
  1757. {
  1758. int s = 0;
  1759. for (int i = 0; i < cols; i++)
  1760. s += value[j, i];
  1761. sum[j] = s;
  1762. }
  1763. }
  1764. else
  1765. {
  1766. throw new ArgumentException("Invalid dimension", "dimension");
  1767. }
  1768. return sum;
  1769. }
  1770. /// <summary>
  1771. /// Gets the sum of all elements in a vector.
  1772. /// </summary>
  1773. public static double Sum(this double[] value)
  1774. {
  1775. double sum = 0.0;
  1776. for (int i = 0; i < value.Length; i++)
  1777. sum += value[i];
  1778. return sum;
  1779. }
  1780. /// <summary>
  1781. /// Gets the product of all elements in a vector.
  1782. /// </summary>
  1783. public static double Product(this double[] value)
  1784. {
  1785. double product = 1.0;
  1786. for (int i = 0; i < value.Length; i++)
  1787. product *= value[i];
  1788. return product;
  1789. }
  1790. /// <summary>
  1791. /// Gets the sum of all elements in a vector.
  1792. /// </summary>
  1793. public static int Sum(this int[] value)
  1794. {
  1795. int sum = 0;
  1796. for (int i = 0; i < value.Length; i++)
  1797. sum += value[i];
  1798. return sum;
  1799. }
  1800. /// <summary>
  1801. /// Gets the product of all elements in a vector.
  1802. /// </summary>
  1803. public static int Product(this int[] value)
  1804. {
  1805. int product = 1;
  1806. for (int i = 0; i < value.Length; i++)
  1807. product *= value[i];
  1808. return product;
  1809. }
  1810. /// <summary>
  1811. /// Gets the maximum element in a vector.
  1812. /// </summary>
  1813. public static T Max<T>(this T[] values, out int imax) where T : IComparable
  1814. {
  1815. imax = 0;
  1816. T max = values[0];
  1817. for (int i = 1; i < values.Length; i++)
  1818. {
  1819. if (values[i].CompareTo(max) > 0)
  1820. {
  1821. max = values[i];
  1822. imax = i;
  1823. }
  1824. }
  1825. return max;
  1826. }
  1827. /// <summary>
  1828. /// Gets the maximum element in a vector.
  1829. /// </summary>
  1830. public static T Max<T>(this T[] values) where T : IComparable
  1831. {
  1832. int imax = 0;
  1833. T max = values[0];
  1834. for (int i = 1; i < values.Length; i++)
  1835. {
  1836. if (values[i].CompareTo(max) > 0)
  1837. {
  1838. max = values[i];
  1839. imax = i;
  1840. }
  1841. }
  1842. return max;
  1843. }
  1844. /// <summary>
  1845. /// Gets the maximum element in a vector.
  1846. /// </summary>
  1847. public static double Max(this double[] vector)
  1848. {
  1849. double max = vector[0];
  1850. for (int i = 0; i < vector.Length; i++)
  1851. {
  1852. if (vector[i] > max)
  1853. max = vector[i];
  1854. }
  1855. return max;
  1856. }
  1857. /// <summary>
  1858. /// Gets the minimum element in a vector.
  1859. /// </summary>
  1860. public static double Min(this double[] values)
  1861. {
  1862. double min = values[0];
  1863. for (int i = 1; i < values.Length; i++)
  1864. {
  1865. if (values[i] < min)
  1866. min = values[i];
  1867. }
  1868. return min;
  1869. }
  1870. /// <summary>
  1871. /// Gets the maximum element in a vector.
  1872. /// </summary>
  1873. public static double Max(this double[] values, out int imax)
  1874. {
  1875. imax = 0;
  1876. double max = values[0];
  1877. for (int i = 1; i < values.Length; i++)
  1878. {
  1879. if (values[i] > max)
  1880. {
  1881. max = values[i];
  1882. imax = i;
  1883. }
  1884. }
  1885. return max;
  1886. }
  1887. /// <summary>
  1888. /// Gets the minimum element in a vector.
  1889. /// </summary>
  1890. public static double Min(this double[] values, out int imin)
  1891. {
  1892. imin = 0;
  1893. double min = values[0];
  1894. for (int i = 1; i < values.Length; i++)
  1895. {
  1896. if (values[i] < min)
  1897. {
  1898. min = values[i];
  1899. imin = i;
  1900. }
  1901. }
  1902. return min;
  1903. }
  1904. /// <summary>
  1905. /// Gets the maximum element in a vector.
  1906. /// </summary>
  1907. public static float Max(this float[] values)
  1908. {
  1909. float max = values[0];
  1910. for (int i = 0; i < values.Length; i++)
  1911. {
  1912. if (values[i] > max)
  1913. max = values[i];
  1914. }
  1915. return max;
  1916. }
  1917. /// <summary>
  1918. /// Gets the minimum element in a vector.
  1919. /// </summary>
  1920. public static float Min(this float[] values)
  1921. {
  1922. float min = values[0];
  1923. for (int i = 1; i < values.Length; i++)
  1924. {
  1925. if (values[i] < min)
  1926. min = values[i];
  1927. }
  1928. return min;
  1929. }
  1930. /// <summary>
  1931. /// Gets the maximum element in a vector.
  1932. /// </summary>
  1933. public static int Max(this int[] values)
  1934. {
  1935. int max = values[0];
  1936. for (int i = 0; i < values.Length; i++)
  1937. {
  1938. if (values[i] > max)
  1939. max = values[i];
  1940. }
  1941. return max;
  1942. }
  1943. /// <summary>
  1944. /// Gets the minimum element in a vector.
  1945. /// </summary>
  1946. public static int Min(this int[] values)
  1947. {
  1948. int min = values[0];
  1949. for (int i = 1; i < values.Length; i++)
  1950. {
  1951. if (values[i] < min)
  1952. min = values[i];
  1953. }
  1954. return min;
  1955. }
  1956. /// <summary>
  1957. /// Gets the maximum values accross one dimension of a matrix.
  1958. /// </summary>
  1959. public static double[] Max(double[,] matrix, int dimension, out int[] imax)
  1960. {
  1961. int rows = matrix.GetLength(0);
  1962. int cols = matrix.GetLength(1);
  1963. double[] max;
  1964. if (dimension == 1) // Search down columns
  1965. {
  1966. imax = new int[rows];
  1967. max = matrix.GetColumn(0);
  1968. for (int j = 0; j < rows; j++)
  1969. {
  1970. for (int i = 1; i < cols; i++)
  1971. {
  1972. if (matrix[j, i] > max[j])
  1973. {
  1974. max[j] = matrix[j, i];
  1975. imax[j] = i;
  1976. }
  1977. }
  1978. }
  1979. }
  1980. else
  1981. {
  1982. imax = new int[cols];
  1983. max = matrix.GetRow(0);
  1984. for (int j = 0; j < cols; j++)
  1985. {
  1986. for (int i = 1; i < rows; i++)
  1987. {
  1988. if (matrix[i, j] > max[j])
  1989. {
  1990. max[j] = matrix[i, j];
  1991. imax[j] = i;
  1992. }
  1993. }
  1994. }
  1995. }
  1996. return max;
  1997. }
  1998. /// <summary>
  1999. /// Gets the minimum values across one dimension of a matrix.
  2000. /// </summary>
  2001. public static double[] Min(double[,] matrix, int dimension, out int[] imin)
  2002. {
  2003. int rows = matrix.GetLength(0);
  2004. int cols = matrix.GetLength(1);
  2005. double[] min;
  2006. if (dimension == 1) // Search down columns
  2007. {
  2008. imin = new int[rows];
  2009. min = matrix.GetColumn(0);
  2010. for (int j = 0; j < rows; j++)
  2011. {
  2012. for (int i = 1; i < cols; i++)
  2013. {
  2014. if (matrix[j, i] < min[j])
  2015. {
  2016. min[j] = matrix[j, i];
  2017. imin[j] = i;
  2018. }
  2019. }
  2020. }
  2021. }
  2022. else
  2023. {
  2024. imin = new int[cols];
  2025. min = matrix.GetRow(0);
  2026. for (int j = 0; j < cols; j++)
  2027. {
  2028. for (int i = 1; i < rows; i++)
  2029. {
  2030. if (matrix[i, j] < min[j])
  2031. {
  2032. min[j] = matrix[i, j];
  2033. imin[j] = i;
  2034. }
  2035. }
  2036. }
  2037. }
  2038. return min;
  2039. }
  2040. /// <summary>
  2041. /// Gets the range of the values in a vector.
  2042. /// </summary>
  2043. public static DoubleRange Range(this double[] array)
  2044. {
  2045. double min = array[0];
  2046. double max = array[0];
  2047. for (int i = 1; i < array.Length; i++)
  2048. {
  2049. if (min > array[i])
  2050. min = array[i];
  2051. if (max < array[i])
  2052. max = array[i];
  2053. }
  2054. return new DoubleRange(min, max);
  2055. }
  2056. /// <summary>
  2057. /// Gets the range of the values in a vector.
  2058. /// </summary>
  2059. public static IntRange Range(this int[] array)
  2060. {
  2061. int min = array[0];
  2062. int max = array[0];
  2063. for (int i = 1; i < array.Length; i++)
  2064. {
  2065. if (min > array[i])
  2066. min = array[i];
  2067. if (max < array[i])
  2068. max = array[i];
  2069. }
  2070. return new IntRange(min, max);
  2071. }
  2072. /// <summary>
  2073. /// Gets the range of the values accross the columns of a matrix.
  2074. /// </summary>
  2075. public static DoubleRange[] Range(double[,] value)
  2076. {
  2077. DoubleRange[] ranges = new DoubleRange[value.GetLength(1)];
  2078. for (int j = 0; j < ranges.Length; j++)
  2079. {
  2080. double max = value[0, j];
  2081. double min = value[0, j];
  2082. for (int i = 0; i < value.GetLength(0); i++)
  2083. {
  2084. if (value[i, j] > max)
  2085. max = value[i, j];
  2086. if (value[i, j] < min)
  2087. min = value[i, j];
  2088. }
  2089. ranges[j] = new DoubleRange(min, max);
  2090. }
  2091. return ranges;
  2092. }
  2093. #endregion
  2094. #region Rounding and discretization
  2095. /// <summary>
  2096. /// Rounds a double-precision floating-point matrix to a specified number of fractional digits.
  2097. /// </summary>
  2098. public static double[,] Round(this double[,] a, int decimals)
  2099. {
  2100. double[,] r = new double[a.GetLength(0), a.GetLength(1)];
  2101. for (int i = 0; i < a.GetLength(0); i++)
  2102. for (int j = 0; j < a.GetLength(1); j++)
  2103. r[i, j] = System.Math.Round(a[i, j], decimals);
  2104. return r;
  2105. }
  2106. /// <summary>
  2107. /// Returns the largest integer less than or equal than to the specified
  2108. /// double-precision floating-point number for each element of the matrix.
  2109. /// </summary>
  2110. public static double[,] Floor(this double[,] a)
  2111. {
  2112. double[,] r = new double[a.GetLength(0), a.GetLength(1)];
  2113. for (int i = 0; i < a.GetLength(0); i++)
  2114. for (int j = 0; j < a.GetLength(1); j++)
  2115. r[i, j] = System.Math.Floor(a[i, j]);
  2116. return r;
  2117. }
  2118. /// <summary>
  2119. /// Returns the largest integer greater than or equal than to the specified
  2120. /// double-precision floating-point number for each element of the matrix.
  2121. /// </summary>
  2122. public static double[,] Ceiling(this double[,] a)
  2123. {
  2124. double[,] r = new double[a.GetLength(0), a.GetLength(1)];
  2125. for (int i = 0; i < a.GetLength(0); i++)
  2126. for (int j = 0; j < a.GetLength(1); j++)
  2127. r[i, j] = System.Math.Ceiling(a[i, j]);
  2128. return r;
  2129. }
  2130. /// <summary>
  2131. /// Rounds a double-precision floating-point number array to a specified number of fractional digits.
  2132. /// </summary>
  2133. public static double[] Round(double[] value, int decimals)
  2134. {
  2135. double[] r = new double[value.Length];
  2136. for (int i = 0; i < r.Length; i++)
  2137. r[i] = Math.Round(value[i], decimals);
  2138. return r;
  2139. }
  2140. /// <summary>
  2141. /// Returns the largest integer less than or equal than to the specified
  2142. /// double-precision floating-point number for each element of the array.
  2143. /// </summary>
  2144. public static double[] Floor(double[] value)
  2145. {
  2146. double[] r = new double[value.Length];
  2147. for (int i = 0; i < r.Length; i++)
  2148. r[i] = Math.Floor(value[i]);
  2149. return r;
  2150. }
  2151. /// <summary>
  2152. /// Returns the largest integer greater than or equal than to the specified
  2153. /// double-precision floating-point number for each element of the array.
  2154. /// </summary>
  2155. public static double[] Ceiling(double[] value)
  2156. {
  2157. double[] r = new double[value.Length];
  2158. for (int i = 0; i < r.Length; i++)
  2159. r[i] = Math.Ceiling(value[i]);
  2160. return r;
  2161. }
  2162. #endregion
  2163. #region Elementwise operations
  2164. /// <summary>
  2165. /// Elementwise absolute value.
  2166. /// </summary>
  2167. public static int[] Abs(this int[] value)
  2168. {
  2169. int[] r = new int[value.Length];
  2170. for (int i = 0; i < value.Length; i++)
  2171. r[i] = System.Math.Abs(value[i]);
  2172. return r;
  2173. }
  2174. /// <summary>
  2175. /// Elementwise absolute value.
  2176. /// </summary>
  2177. public static double[] Abs(this double[] value)
  2178. {
  2179. double[] r = new double[value.Length];
  2180. for (int i = 0; i < value.Length; i++)
  2181. r[i] = System.Math.Abs(value[i]);
  2182. return r;
  2183. }
  2184. /// <summary>
  2185. /// Elementwise absolute value.
  2186. /// </summary>
  2187. public static double[,] Abs(this double[,] value)
  2188. {
  2189. int rows = value.GetLength(0);
  2190. int cols = value.GetLength(1);
  2191. double[,] r = new double[rows, cols];
  2192. for (int i = 0; i < rows; i++)
  2193. for (int j = 0; j < cols; j++)
  2194. r[i, j] = System.Math.Abs(value[i, j]);
  2195. return r;
  2196. }
  2197. /// <summary>
  2198. /// Elementwise absolute value.
  2199. /// </summary>
  2200. public static int[,] Abs(this int[,] value)
  2201. {
  2202. int rows = value.GetLength(0);
  2203. int cols = value.GetLength(1);
  2204. int[,] r = new int[rows, cols];
  2205. for (int i = 0; i < rows; i++)
  2206. for (int j = 0; j < cols; j++)
  2207. r[i, j] = System.Math.Abs(value[i, j]);
  2208. return r;
  2209. }
  2210. /// <summary>
  2211. /// Elementwise Square root.
  2212. /// </summary>
  2213. public static double[] Sqrt(this double[] value)
  2214. {
  2215. double[] r = new double[value.Length];
  2216. for (int i = 0; i < value.Length; i++)
  2217. r[i] = System.Math.Sqrt(value[i]);
  2218. return r;
  2219. }
  2220. /// <summary>
  2221. /// Elementwise Square root.
  2222. /// </summary>
  2223. public static double[,] Sqrt(this double[,] value)
  2224. {
  2225. int rows = value.GetLength(0);
  2226. int cols = value.GetLength(1);
  2227. double[,] r = new double[rows, cols];
  2228. for (int i = 0; i < rows; i++)
  2229. for (int j = 0; j < cols; j++)
  2230. r[i, j] = System.Math.Sqrt(value[i, j]);
  2231. return r;
  2232. }
  2233. /// <summary>
  2234. /// Elementwise power operation.
  2235. /// </summary>
  2236. /// <param name="x">A matrix.</param>
  2237. /// <param name="y">A power.</param>
  2238. /// <returns>Returns x elevated to the power of y.</returns>
  2239. public static double[,] ElementwisePower(this double[,] x, double y)
  2240. {
  2241. double[,] r = new double[x.GetLength(0), x.GetLength(1)];
  2242. for (int i = 0; i < x.GetLength(0); i++)
  2243. for (int j = 0; j < x.GetLength(1); j++)
  2244. r[i, j] = System.Math.Pow(x[i, j], y);
  2245. return r;
  2246. }
  2247. /// <summary>
  2248. /// Elementwise power operation.
  2249. /// </summary>
  2250. /// <param name="x">A matrix.</param>
  2251. /// <param name="y">A power.</param>
  2252. /// <returns>Returns x elevated to the power of y.</returns>
  2253. public static double[] ElementwisePower(this double[] x, double y)
  2254. {
  2255. double[] r = new double[x.Length];
  2256. for (int i = 0; i < r.Length; i++)
  2257. r[i] = System.Math.Pow(x[i], y);
  2258. return r;
  2259. }
  2260. /// <summary>
  2261. /// Elementwise divide operation.
  2262. /// </summary>
  2263. public static double[] ElementwiseDivide(this double[] a, double[] b)
  2264. {
  2265. double[] r = new double[a.Length];
  2266. for (int i = 0; i < a.Length; i++)
  2267. r[i] = a[i] / b[i];
  2268. return r;
  2269. }
  2270. /// <summary>
  2271. /// Elementwise divide operation.
  2272. /// </summary>
  2273. public static double[,] ElementwiseDivide(this double[,] a, double[,] b)
  2274. {
  2275. int rows = a.GetLength(0);
  2276. int cols = b.GetLength(1);
  2277. double[,] r = new double[rows, cols];
  2278. for (int i = 0; i < rows; i++)
  2279. for (int j = 0; j < cols; j++)
  2280. r[i, j] = a[i, j] / b[i, j];
  2281. return r;
  2282. }
  2283. /// <summary>
  2284. /// Elementwise division.
  2285. /// </summary>
  2286. public static double[,] ElementwiseDivide(this double[,] a, double[] b, int dimension)
  2287. {
  2288. int rows = a.GetLength(0);
  2289. int cols = a.GetLength(1);
  2290. double[,] r = new double[rows, cols];
  2291. if (dimension == 1)
  2292. {
  2293. if (cols != b.Length) throw new ArgumentException(
  2294. "Length of B should equal the number of columns in A", "b");
  2295. for (int i = 0; i < rows; i++)
  2296. for (int j = 0; j < cols; j++)
  2297. r[i, j] = a[i, j] / b[j];
  2298. }
  2299. else
  2300. {
  2301. if (rows != b.Length) throw new ArgumentException(
  2302. "Length of B should equal the number of rows in A", "b");
  2303. for (int j = 0; j < cols; j++)
  2304. for (int i = 0; i < rows; i++)
  2305. r[i, j] = a[i, j] / b[i];
  2306. }
  2307. return r;
  2308. }
  2309. /// <summary>
  2310. /// Elementwise multiply operation.
  2311. /// </summary>
  2312. public static double[] ElementwiseMultiply(this double[] a, double[] b)
  2313. {
  2314. double[] r = new double[a.Length];
  2315. for (int i = 0; i < a.Length; i++)
  2316. r[i] = a[i] * b[i];
  2317. return r;
  2318. }
  2319. /// <summary>
  2320. /// Elementwise multiply operation.
  2321. /// </summary>
  2322. public static double[,] ElementwiseMultiply(this double[,] a, double[,] b)
  2323. {
  2324. if (a.GetLength(0) != b.GetLength(0) || a.GetLength(1) != b.GetLength(1))
  2325. throw new ArgumentException("Matrix dimensions must agree.", "b");
  2326. int rows = a.GetLength(0);
  2327. int cols = a.GetLength(1);
  2328. double[,] r = new double[rows, cols];
  2329. for (int i = 0; i < rows; i++)
  2330. for (int j = 0; j < cols; j++)
  2331. r[i, j] = a[i, j] * b[i, j];
  2332. return r;
  2333. }
  2334. /// <summary>
  2335. /// Elementwise multiply operation.
  2336. /// </summary>
  2337. public static int[] ElementwiseMultiply(this int[] a, int[] b)
  2338. {
  2339. int[] r = new int[a.Length];
  2340. for (int i = 0; i < a.Length; i++)
  2341. r[i] = a[i] * b[i];
  2342. return r;
  2343. }
  2344. /// <summary>
  2345. /// Elementwise multiplication.
  2346. /// </summary>
  2347. public static int[,] ElementwiseMultiply(this int[,] a, int[,] b)
  2348. {
  2349. if (a.GetLength(0) != b.GetLength(0) || a.GetLength(1) != b.GetLength(1))
  2350. throw new ArgumentException("Matrix dimensions must agree.", "b");
  2351. int rows = a.GetLength(0);
  2352. int cols = a.GetLength(1);
  2353. int[,] r = new int[rows, cols];
  2354. for (int i = 0; i < rows; i++)
  2355. for (int j = 0; j < cols; j++)
  2356. r[i, j] = a[i, j] * b[i, j];
  2357. return r;
  2358. }
  2359. /// <summary>
  2360. /// Elementwise multiplication.
  2361. /// </summary>
  2362. public static double[,] ElementwiseMultiply(this double[,] a, double[] b, int dimension)
  2363. {
  2364. int rows = a.GetLength(0);
  2365. int cols = a.GetLength(1);
  2366. double[,] r = new double[rows, cols];
  2367. if (dimension == 1)
  2368. {
  2369. if (cols != b.Length) throw new ArgumentException(
  2370. "Length of B should equal the number of columns in A", "b");
  2371. for (int i = 0; i < rows; i++)
  2372. for (int j = 0; j < cols; j++)
  2373. r[i, j] = a[i, j] * b[j];
  2374. }
  2375. else
  2376. {
  2377. if (rows != b.Length) throw new ArgumentException(
  2378. "Length of B should equal the number of rows in A", "b");
  2379. for (int j = 0; j < cols; j++)
  2380. for (int i = 0; i < rows; i++)
  2381. r[i, j] = a[i, j] * b[i];
  2382. }
  2383. return r;
  2384. }
  2385. #endregion
  2386. #region Conversions
  2387. /// <summary>
  2388. /// Converts a jagged-array into a multidimensional array.
  2389. /// </summary>
  2390. public static T[,] ToMatrix<T>(this T[][] array)
  2391. {
  2392. int rows = array.Length;
  2393. if (rows == 0) return new T[rows, 0];
  2394. int cols = array[0].Length;
  2395. T[,] m = new T[rows, cols];
  2396. for (int i = 0; i < rows; i++)
  2397. for (int j = 0; j < cols; j++)
  2398. m[i, j] = array[i][j];
  2399. return m;
  2400. }
  2401. /// <summary>
  2402. /// Converts an array into a multidimensional array.
  2403. /// </summary>
  2404. public static T[,] ToMatrix<T>(this T[] array)
  2405. {
  2406. T[,] m = new T[1, array.Length];
  2407. for (int i = 0; i < array.Length; i++)
  2408. m[0, i] = array[i];
  2409. return m;
  2410. }
  2411. /// <summary>
  2412. /// Converts a multidimensional array into a jagged-array.
  2413. /// </summary>
  2414. public static T[][] ToArray<T>(this T[,] matrix)
  2415. {
  2416. int rows = matrix.GetLength(0);
  2417. T[][] array = new T[rows][];
  2418. for (int i = 0; i < rows; i++)
  2419. array[i] = matrix.GetRow(i);
  2420. return array;
  2421. }
  2422. /// <summary>
  2423. /// Converts a DataTable to a double[,] array.
  2424. /// </summary>
  2425. public static double[,] ToMatrix(this DataTable table, out string[] columnNames)
  2426. {
  2427. double[,] m = new double[table.Rows.Count, table.Columns.Count];
  2428. columnNames = new string[table.Columns.Count];
  2429. for (int j = 0; j < table.Columns.Count; j++)
  2430. {
  2431. for (int i = 0; i < table.Rows.Count; i++)
  2432. {
  2433. if (table.Columns[j].DataType == typeof(System.String))
  2434. {
  2435. m[i, j] = Double.Parse((String)table.Rows[i][j], System.Globalization.CultureInfo.InvariantCulture);
  2436. }
  2437. else if (table.Columns[j].DataType == typeof(System.Boolean))
  2438. {
  2439. m[i, j] = (Boolean)table.Rows[i][j] ? 1.0 : 0.0;
  2440. }
  2441. else
  2442. {
  2443. m[i, j] = (Double)table.Rows[i][j];
  2444. }
  2445. }
  2446. columnNames[j] = table.Columns[j].Caption;
  2447. }
  2448. return m;
  2449. }
  2450. /// <summary>
  2451. /// Converts a DataTable to a double[,] array.
  2452. /// </summary>
  2453. public static double[,] ToMatrix(this DataTable table)
  2454. {
  2455. String[] names;
  2456. return ToMatrix(table, out names);
  2457. }
  2458. /// <summary>
  2459. /// Converts a DataTable to a double[][] array.
  2460. /// </summary>
  2461. public static double[][] ToArray(this DataTable table)
  2462. {
  2463. double[][] m = new double[table.Rows.Count][];
  2464. for (int i = 0; i < table.Rows.Count; i++)
  2465. {
  2466. m[i] = new double[table.Columns.Count];
  2467. for (int j = 0; j < table.Columns.Count; j++)
  2468. {
  2469. if (table.Columns[j].DataType == typeof(System.String))
  2470. {
  2471. m[i][j] = Double.Parse((String)table.Rows[i][j], System.Globalization.CultureInfo.InvariantCulture);
  2472. }
  2473. else if (table.Columns[j].DataType == typeof(System.Boolean))
  2474. {
  2475. m[i][j] = (Boolean)table.Rows[i][j] ? 1.0 : 0.0;
  2476. }
  2477. else
  2478. {
  2479. m[i][j] = (Double)table.Rows[i][j];
  2480. }
  2481. }
  2482. }
  2483. return m;
  2484. }
  2485. /// <summary>
  2486. /// Converts a DataColumn to a double[] array.
  2487. /// </summary>
  2488. public static double[] ToArray(this DataColumn column)
  2489. {
  2490. double[] m = new double[column.Table.Rows.Count];
  2491. for (int i = 0; i < m.Length; i++)
  2492. {
  2493. object b = column.Table.Rows[i][column];
  2494. if (column.DataType == typeof(System.String))
  2495. {
  2496. m[i] = Double.Parse((String)b, System.Globalization.CultureInfo.InvariantCulture);
  2497. }
  2498. else if (column.DataType == typeof(System.Boolean))
  2499. {
  2500. m[i] = (Boolean)b ? 1.0 : 0.0;
  2501. }
  2502. else
  2503. {
  2504. m[i] = (Double)b;
  2505. }
  2506. }
  2507. return m;
  2508. }
  2509. #endregion
  2510. #region Inverses and Linear System Solving
  2511. /// <summary>
  2512. /// Returns the LHS solution matrix if the matrix is square or the least squares solution otherwise.
  2513. /// </summary>
  2514. /// <remarks>
  2515. /// Please note that this does not check if the matrix is non-singular before attempting to solve.
  2516. /// </remarks>
  2517. public static double[,] Solve(this double[,] matrix, double[,] rightSide)
  2518. {
  2519. if (matrix.GetLength(0) == matrix.GetLength(1))
  2520. {
  2521. // Solve by LU Decomposition if matrix is square.
  2522. return new LuDecomposition(matrix).Solve(rightSide);
  2523. }
  2524. else
  2525. {
  2526. // Solve by QR Decomposition if not.
  2527. return new QrDecomposition(matrix).Solve(rightSide);
  2528. }
  2529. }
  2530. /// <summary>
  2531. /// Returns the LHS solution vector if the matrix is square or the least squares solution otherwise.
  2532. /// </summary>
  2533. /// <remarks>
  2534. /// Please note that this does not check if the matrix is non-singular before attempting to solve.
  2535. /// </remarks>
  2536. public static double[] Solve(this double[,] matrix, double[] rightSide)
  2537. {
  2538. if (matrix.GetLength(0) == matrix.GetLength(1))
  2539. {
  2540. // Solve by LU Decomposition if matrix is square.
  2541. return new LuDecomposition(matrix).Solve(rightSide);
  2542. }
  2543. else
  2544. {
  2545. // Solve by QR Decomposition if not.
  2546. return new QrDecomposition(matrix).Solve(rightSide);
  2547. }
  2548. }
  2549. /// <summary>
  2550. /// Computes the inverse of a matrix.
  2551. /// </summary>
  2552. public static double[,] Inverse(this double[,] matrix)
  2553. {
  2554. if (matrix.GetLength(0) != matrix.GetLength(1))
  2555. throw new ArgumentException("Matrix must be square", "matrix");
  2556. return new LuDecomposition(matrix).Inverse();
  2557. }
  2558. /// <summary>
  2559. /// Computes the pseudo-inverse of a matrix.
  2560. /// </summary>
  2561. public static double[,] PseudoInverse(this double[,] matrix)
  2562. {
  2563. return new SingularValueDecomposition(matrix, true, true, true).Inverse();
  2564. }
  2565. #endregion
  2566. #region Morphological operations
  2567. /// <summary>
  2568. /// Transforms a vector into a matrix of given dimensions.
  2569. /// </summary>
  2570. public static T[,] Reshape<T>(T[] array, int rows, int cols)
  2571. {
  2572. T[,] r = new T[rows, cols];
  2573. for (int j = 0, k = 0; j < cols; j++)
  2574. for (int i = 0; i < rows; i++)
  2575. r[i, j] = array[k++];
  2576. return r;
  2577. }
  2578. /// <summary>
  2579. /// Transforms a vector into a single vector.
  2580. /// </summary>
  2581. public static T[] Reshape<T>(T[,] array, int dimension)
  2582. {
  2583. int rows = array.GetLength(0);
  2584. int cols = array.GetLength(1);
  2585. T[] r = new T[rows * cols];
  2586. if (dimension == 1)
  2587. {
  2588. for (int j = 0, k = 0; j < rows; j++)
  2589. for (int i = 0; i < cols; i++)
  2590. r[k++] = array[j, i];
  2591. }
  2592. else
  2593. {
  2594. for (int i = 0, k = 0; i < cols; i++)
  2595. for (int j = 0; j < rows; j++)
  2596. r[k++] = array[j, i];
  2597. }
  2598. return r;
  2599. }
  2600. #endregion
  2601. }
  2602. }