matrixbase.py 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428
  1. from __future__ import annotations
  2. from collections import defaultdict
  3. from collections.abc import Iterable
  4. from inspect import isfunction
  5. from functools import reduce
  6. from sympy.assumptions.refine import refine
  7. from sympy.core import SympifyError, Add
  8. from sympy.core.basic import Atom, Basic
  9. from sympy.core.kind import UndefinedKind
  10. from sympy.core.numbers import Integer
  11. from sympy.core.mod import Mod
  12. from sympy.core.symbol import Symbol, Dummy
  13. from sympy.core.sympify import sympify, _sympify
  14. from sympy.core.function import diff
  15. from sympy.polys import cancel
  16. from sympy.functions.elementary.complexes import Abs, re, im
  17. from sympy.printing import sstr
  18. from sympy.functions.elementary.miscellaneous import Max, Min, sqrt
  19. from sympy.functions.special.tensor_functions import KroneckerDelta, LeviCivita
  20. from sympy.core.singleton import S
  21. from sympy.printing.defaults import Printable
  22. from sympy.printing.str import StrPrinter
  23. from sympy.functions.elementary.exponential import exp, log
  24. from sympy.functions.combinatorial.factorials import binomial, factorial
  25. import mpmath as mp
  26. from collections.abc import Callable
  27. from sympy.utilities.iterables import reshape
  28. from sympy.core.expr import Expr
  29. from sympy.core.power import Pow
  30. from sympy.core.symbol import uniquely_named_symbol
  31. from .utilities import _dotprodsimp, _simplify as _utilities_simplify
  32. from sympy.polys.polytools import Poly
  33. from sympy.utilities.iterables import flatten, is_sequence
  34. from sympy.utilities.misc import as_int, filldedent
  35. from sympy.core.decorators import call_highest_priority
  36. from sympy.core.logic import fuzzy_and, FuzzyBool
  37. from sympy.tensor.array import NDimArray
  38. from sympy.utilities.iterables import NotIterable
  39. from .utilities import _get_intermediate_simp_bool
  40. from .kind import MatrixKind
  41. from .exceptions import (
  42. MatrixError, ShapeError, NonSquareMatrixError, NonInvertibleMatrixError,
  43. )
  44. from .utilities import _iszero, _is_zero_after_expand_mul
  45. from .determinant import (
  46. _find_reasonable_pivot, _find_reasonable_pivot_naive,
  47. _adjugate, _charpoly, _cofactor, _cofactor_matrix, _per,
  48. _det, _det_bareiss, _det_berkowitz, _det_bird, _det_laplace, _det_LU,
  49. _minor, _minor_submatrix)
  50. from .reductions import _is_echelon, _echelon_form, _rank, _rref
  51. from .solvers import (
  52. _diagonal_solve, _lower_triangular_solve, _upper_triangular_solve,
  53. _cholesky_solve, _LDLsolve, _LUsolve, _QRsolve, _gauss_jordan_solve,
  54. _pinv_solve, _cramer_solve, _solve, _solve_least_squares)
  55. from .inverse import (
  56. _pinv, _inv_ADJ, _inv_GE, _inv_LU, _inv_CH, _inv_LDL, _inv_QR,
  57. _inv, _inv_block)
  58. from .subspaces import _columnspace, _nullspace, _rowspace, _orthogonalize
  59. from .eigen import (
  60. _eigenvals, _eigenvects,
  61. _bidiagonalize, _bidiagonal_decomposition,
  62. _is_diagonalizable, _diagonalize,
  63. _is_positive_definite, _is_positive_semidefinite,
  64. _is_negative_definite, _is_negative_semidefinite, _is_indefinite,
  65. _jordan_form, _left_eigenvects, _singular_values)
  66. from .decompositions import (
  67. _rank_decomposition, _cholesky, _LDLdecomposition,
  68. _LUdecomposition, _LUdecomposition_Simple, _LUdecompositionFF,
  69. _singular_value_decomposition, _QRdecomposition, _upper_hessenberg_decomposition)
  70. from .graph import (
  71. _connected_components, _connected_components_decomposition,
  72. _strongly_connected_components, _strongly_connected_components_decomposition)
  73. __doctest_requires__ = {
  74. ('MatrixBase.is_indefinite',
  75. 'MatrixBase.is_positive_definite',
  76. 'MatrixBase.is_positive_semidefinite',
  77. 'MatrixBase.is_negative_definite',
  78. 'MatrixBase.is_negative_semidefinite'): ['matplotlib'],
  79. }
  80. class MatrixBase(Printable):
  81. """All common matrix operations including basic arithmetic, shaping,
  82. and special matrices like `zeros`, and `eye`."""
  83. _op_priority = 10.01
  84. # Added just for numpy compatibility
  85. __array_priority__ = 11
  86. is_Matrix = True
  87. _class_priority = 3
  88. _sympify = staticmethod(sympify)
  89. zero = S.Zero
  90. one = S.One
  91. _diff_wrt: bool = True
  92. rows: int
  93. cols: int
  94. _simplify = None
  95. @classmethod
  96. def _new(cls, *args, **kwargs):
  97. """`_new` must, at minimum, be callable as
  98. `_new(rows, cols, mat) where mat is a flat list of the
  99. elements of the matrix."""
  100. raise NotImplementedError("Subclasses must implement this.")
  101. def __eq__(self, other):
  102. raise NotImplementedError("Subclasses must implement this.")
  103. def __getitem__(self, key):
  104. """Implementations of __getitem__ should accept ints, in which
  105. case the matrix is indexed as a flat list, tuples (i,j) in which
  106. case the (i,j) entry is returned, slices, or mixed tuples (a,b)
  107. where a and b are any combination of slices and integers."""
  108. raise NotImplementedError("Subclasses must implement this.")
  109. @property
  110. def shape(self):
  111. """The shape (dimensions) of the matrix as the 2-tuple (rows, cols).
  112. Examples
  113. ========
  114. >>> from sympy import zeros
  115. >>> M = zeros(2, 3)
  116. >>> M.shape
  117. (2, 3)
  118. >>> M.rows
  119. 2
  120. >>> M.cols
  121. 3
  122. """
  123. return (self.rows, self.cols)
  124. def _eval_col_del(self, col):
  125. def entry(i, j):
  126. return self[i, j] if j < col else self[i, j + 1]
  127. return self._new(self.rows, self.cols - 1, entry)
  128. def _eval_col_insert(self, pos, other):
  129. def entry(i, j):
  130. if j < pos:
  131. return self[i, j]
  132. elif pos <= j < pos + other.cols:
  133. return other[i, j - pos]
  134. return self[i, j - other.cols]
  135. return self._new(self.rows, self.cols + other.cols, entry)
  136. def _eval_col_join(self, other):
  137. rows = self.rows
  138. def entry(i, j):
  139. if i < rows:
  140. return self[i, j]
  141. return other[i - rows, j]
  142. return classof(self, other)._new(self.rows + other.rows, self.cols,
  143. entry)
  144. def _eval_extract(self, rowsList, colsList):
  145. mat = list(self)
  146. cols = self.cols
  147. indices = (i * cols + j for i in rowsList for j in colsList)
  148. return self._new(len(rowsList), len(colsList),
  149. [mat[i] for i in indices])
  150. def _eval_get_diag_blocks(self):
  151. sub_blocks = []
  152. def recurse_sub_blocks(M):
  153. for i in range(1, M.shape[0] + 1):
  154. if i == 1:
  155. to_the_right = M[0, i:]
  156. to_the_bottom = M[i:, 0]
  157. else:
  158. to_the_right = M[:i, i:]
  159. to_the_bottom = M[i:, :i]
  160. if any(to_the_right) or any(to_the_bottom):
  161. continue
  162. sub_blocks.append(M[:i, :i])
  163. if M.shape != M[:i, :i].shape:
  164. recurse_sub_blocks(M[i:, i:])
  165. return
  166. recurse_sub_blocks(self)
  167. return sub_blocks
  168. def _eval_row_del(self, row):
  169. def entry(i, j):
  170. return self[i, j] if i < row else self[i + 1, j]
  171. return self._new(self.rows - 1, self.cols, entry)
  172. def _eval_row_insert(self, pos, other):
  173. entries = list(self)
  174. insert_pos = pos * self.cols
  175. entries[insert_pos:insert_pos] = list(other)
  176. return self._new(self.rows + other.rows, self.cols, entries)
  177. def _eval_row_join(self, other):
  178. cols = self.cols
  179. def entry(i, j):
  180. if j < cols:
  181. return self[i, j]
  182. return other[i, j - cols]
  183. return classof(self, other)._new(self.rows, self.cols + other.cols,
  184. entry)
  185. def _eval_tolist(self):
  186. return [list(self[i,:]) for i in range(self.rows)]
  187. def _eval_todok(self):
  188. dok = {}
  189. rows, cols = self.shape
  190. for i in range(rows):
  191. for j in range(cols):
  192. val = self[i, j]
  193. if val != self.zero:
  194. dok[i, j] = val
  195. return dok
  196. @classmethod
  197. def _eval_from_dok(cls, rows, cols, dok):
  198. out_flat = [cls.zero] * (rows * cols)
  199. for (i, j), val in dok.items():
  200. out_flat[i * cols + j] = val
  201. return cls._new(rows, cols, out_flat)
  202. def _eval_vec(self):
  203. rows = self.rows
  204. def entry(n, _):
  205. # we want to read off the columns first
  206. j = n // rows
  207. i = n - j * rows
  208. return self[i, j]
  209. return self._new(len(self), 1, entry)
  210. def _eval_vech(self, diagonal):
  211. c = self.cols
  212. v = []
  213. if diagonal:
  214. for j in range(c):
  215. for i in range(j, c):
  216. v.append(self[i, j])
  217. else:
  218. for j in range(c):
  219. for i in range(j + 1, c):
  220. v.append(self[i, j])
  221. return self._new(len(v), 1, v)
  222. def col_del(self, col):
  223. """Delete the specified column."""
  224. if col < 0:
  225. col += self.cols
  226. if not 0 <= col < self.cols:
  227. raise IndexError("Column {} is out of range.".format(col))
  228. return self._eval_col_del(col)
  229. def col_insert(self, pos, other):
  230. """Insert one or more columns at the given column position.
  231. Examples
  232. ========
  233. >>> from sympy import zeros, ones
  234. >>> M = zeros(3)
  235. >>> V = ones(3, 1)
  236. >>> M.col_insert(1, V)
  237. Matrix([
  238. [0, 1, 0, 0],
  239. [0, 1, 0, 0],
  240. [0, 1, 0, 0]])
  241. See Also
  242. ========
  243. col
  244. row_insert
  245. """
  246. # Allows you to build a matrix even if it is null matrix
  247. if not self:
  248. return type(self)(other)
  249. pos = as_int(pos)
  250. if pos < 0:
  251. pos = self.cols + pos
  252. if pos < 0:
  253. pos = 0
  254. elif pos > self.cols:
  255. pos = self.cols
  256. if self.rows != other.rows:
  257. raise ShapeError(
  258. "The matrices have incompatible number of rows ({} and {})"
  259. .format(self.rows, other.rows))
  260. return self._eval_col_insert(pos, other)
  261. def col_join(self, other):
  262. """Concatenates two matrices along self's last and other's first row.
  263. Examples
  264. ========
  265. >>> from sympy import zeros, ones
  266. >>> M = zeros(3)
  267. >>> V = ones(1, 3)
  268. >>> M.col_join(V)
  269. Matrix([
  270. [0, 0, 0],
  271. [0, 0, 0],
  272. [0, 0, 0],
  273. [1, 1, 1]])
  274. See Also
  275. ========
  276. col
  277. row_join
  278. """
  279. # A null matrix can always be stacked (see #10770)
  280. if self.rows == 0 and self.cols != other.cols:
  281. return self._new(0, other.cols, []).col_join(other)
  282. if self.cols != other.cols:
  283. raise ShapeError(
  284. "The matrices have incompatible number of columns ({} and {})"
  285. .format(self.cols, other.cols))
  286. return self._eval_col_join(other)
  287. def col(self, j):
  288. """Elementary column selector.
  289. Examples
  290. ========
  291. >>> from sympy import eye
  292. >>> eye(2).col(0)
  293. Matrix([
  294. [1],
  295. [0]])
  296. See Also
  297. ========
  298. row
  299. col_del
  300. col_join
  301. col_insert
  302. """
  303. return self[:, j]
  304. def extract(self, rowsList, colsList):
  305. r"""Return a submatrix by specifying a list of rows and columns.
  306. Negative indices can be given. All indices must be in the range
  307. $-n \le i < n$ where $n$ is the number of rows or columns.
  308. Examples
  309. ========
  310. >>> from sympy import Matrix
  311. >>> m = Matrix(4, 3, range(12))
  312. >>> m
  313. Matrix([
  314. [0, 1, 2],
  315. [3, 4, 5],
  316. [6, 7, 8],
  317. [9, 10, 11]])
  318. >>> m.extract([0, 1, 3], [0, 1])
  319. Matrix([
  320. [0, 1],
  321. [3, 4],
  322. [9, 10]])
  323. Rows or columns can be repeated:
  324. >>> m.extract([0, 0, 1], [-1])
  325. Matrix([
  326. [2],
  327. [2],
  328. [5]])
  329. Every other row can be taken by using range to provide the indices:
  330. >>> m.extract(range(0, m.rows, 2), [-1])
  331. Matrix([
  332. [2],
  333. [8]])
  334. RowsList or colsList can also be a list of booleans, in which case
  335. the rows or columns corresponding to the True values will be selected:
  336. >>> m.extract([0, 1, 2, 3], [True, False, True])
  337. Matrix([
  338. [0, 2],
  339. [3, 5],
  340. [6, 8],
  341. [9, 11]])
  342. """
  343. if not is_sequence(rowsList) or not is_sequence(colsList):
  344. raise TypeError("rowsList and colsList must be iterable")
  345. # ensure rowsList and colsList are lists of integers
  346. if rowsList and all(isinstance(i, bool) for i in rowsList):
  347. rowsList = [index for index, item in enumerate(rowsList) if item]
  348. if colsList and all(isinstance(i, bool) for i in colsList):
  349. colsList = [index for index, item in enumerate(colsList) if item]
  350. # ensure everything is in range
  351. rowsList = [a2idx(k, self.rows) for k in rowsList]
  352. colsList = [a2idx(k, self.cols) for k in colsList]
  353. return self._eval_extract(rowsList, colsList)
  354. def get_diag_blocks(self):
  355. """Obtains the square sub-matrices on the main diagonal of a square matrix.
  356. Useful for inverting symbolic matrices or solving systems of
  357. linear equations which may be decoupled by having a block diagonal
  358. structure.
  359. Examples
  360. ========
  361. >>> from sympy import Matrix
  362. >>> from sympy.abc import x, y, z
  363. >>> A = Matrix([[1, 3, 0, 0], [y, z*z, 0, 0], [0, 0, x, 0], [0, 0, 0, 0]])
  364. >>> a1, a2, a3 = A.get_diag_blocks()
  365. >>> a1
  366. Matrix([
  367. [1, 3],
  368. [y, z**2]])
  369. >>> a2
  370. Matrix([[x]])
  371. >>> a3
  372. Matrix([[0]])
  373. """
  374. return self._eval_get_diag_blocks()
  375. @classmethod
  376. def hstack(cls, *args):
  377. """Return a matrix formed by joining args horizontally (i.e.
  378. by repeated application of row_join).
  379. Examples
  380. ========
  381. >>> from sympy import Matrix, eye
  382. >>> Matrix.hstack(eye(2), 2*eye(2))
  383. Matrix([
  384. [1, 0, 2, 0],
  385. [0, 1, 0, 2]])
  386. """
  387. if len(args) == 0:
  388. return cls._new()
  389. kls = type(args[0])
  390. return reduce(kls.row_join, args)
  391. def reshape(self, rows, cols):
  392. """Reshape the matrix. Total number of elements must remain the same.
  393. Examples
  394. ========
  395. >>> from sympy import Matrix
  396. >>> m = Matrix(2, 3, lambda i, j: 1)
  397. >>> m
  398. Matrix([
  399. [1, 1, 1],
  400. [1, 1, 1]])
  401. >>> m.reshape(1, 6)
  402. Matrix([[1, 1, 1, 1, 1, 1]])
  403. >>> m.reshape(3, 2)
  404. Matrix([
  405. [1, 1],
  406. [1, 1],
  407. [1, 1]])
  408. """
  409. if self.rows * self.cols != rows * cols:
  410. raise ValueError("Invalid reshape parameters %d %d" % (rows, cols))
  411. dok = {divmod(i*self.cols + j, cols):
  412. v for (i, j), v in self.todok().items()}
  413. return self._eval_from_dok(rows, cols, dok)
  414. def row_del(self, row):
  415. """Delete the specified row."""
  416. if row < 0:
  417. row += self.rows
  418. if not 0 <= row < self.rows:
  419. raise IndexError("Row {} is out of range.".format(row))
  420. return self._eval_row_del(row)
  421. def row_insert(self, pos, other):
  422. """Insert one or more rows at the given row position.
  423. Examples
  424. ========
  425. >>> from sympy import zeros, ones
  426. >>> M = zeros(3)
  427. >>> V = ones(1, 3)
  428. >>> M.row_insert(1, V)
  429. Matrix([
  430. [0, 0, 0],
  431. [1, 1, 1],
  432. [0, 0, 0],
  433. [0, 0, 0]])
  434. See Also
  435. ========
  436. row
  437. col_insert
  438. """
  439. # Allows you to build a matrix even if it is null matrix
  440. if not self:
  441. return self._new(other)
  442. pos = as_int(pos)
  443. if pos < 0:
  444. pos = self.rows + pos
  445. if pos < 0:
  446. pos = 0
  447. elif pos > self.rows:
  448. pos = self.rows
  449. if self.cols != other.cols:
  450. raise ShapeError(
  451. "The matrices have incompatible number of columns ({} and {})"
  452. .format(self.cols, other.cols))
  453. return self._eval_row_insert(pos, other)
  454. def row_join(self, other):
  455. """Concatenates two matrices along self's last and rhs's first column
  456. Examples
  457. ========
  458. >>> from sympy import zeros, ones
  459. >>> M = zeros(3)
  460. >>> V = ones(3, 1)
  461. >>> M.row_join(V)
  462. Matrix([
  463. [0, 0, 0, 1],
  464. [0, 0, 0, 1],
  465. [0, 0, 0, 1]])
  466. See Also
  467. ========
  468. row
  469. col_join
  470. """
  471. # A null matrix can always be stacked (see #10770)
  472. if self.cols == 0 and self.rows != other.rows:
  473. return self._new(other.rows, 0, []).row_join(other)
  474. if self.rows != other.rows:
  475. raise ShapeError(
  476. "The matrices have incompatible number of rows ({} and {})"
  477. .format(self.rows, other.rows))
  478. return self._eval_row_join(other)
  479. def diagonal(self, k=0):
  480. """Returns the kth diagonal of self. The main diagonal
  481. corresponds to `k=0`; diagonals above and below correspond to
  482. `k > 0` and `k < 0`, respectively. The values of `self[i, j]`
  483. for which `j - i = k`, are returned in order of increasing
  484. `i + j`, starting with `i + j = |k|`.
  485. Examples
  486. ========
  487. >>> from sympy import Matrix
  488. >>> m = Matrix(3, 3, lambda i, j: j - i); m
  489. Matrix([
  490. [ 0, 1, 2],
  491. [-1, 0, 1],
  492. [-2, -1, 0]])
  493. >>> _.diagonal()
  494. Matrix([[0, 0, 0]])
  495. >>> m.diagonal(1)
  496. Matrix([[1, 1]])
  497. >>> m.diagonal(-2)
  498. Matrix([[-2]])
  499. Even though the diagonal is returned as a Matrix, the element
  500. retrieval can be done with a single index:
  501. >>> Matrix.diag(1, 2, 3).diagonal()[1] # instead of [0, 1]
  502. 2
  503. See Also
  504. ========
  505. diag
  506. """
  507. rv = []
  508. k = as_int(k)
  509. r = 0 if k > 0 else -k
  510. c = 0 if r else k
  511. while True:
  512. if r == self.rows or c == self.cols:
  513. break
  514. rv.append(self[r, c])
  515. r += 1
  516. c += 1
  517. if not rv:
  518. raise ValueError(filldedent('''
  519. The %s diagonal is out of range [%s, %s]''' % (
  520. k, 1 - self.rows, self.cols - 1)))
  521. return self._new(1, len(rv), rv)
  522. def row(self, i):
  523. """Elementary row selector.
  524. Examples
  525. ========
  526. >>> from sympy import eye
  527. >>> eye(2).row(0)
  528. Matrix([[1, 0]])
  529. See Also
  530. ========
  531. col
  532. row_del
  533. row_join
  534. row_insert
  535. """
  536. return self[i, :]
  537. def todok(self):
  538. """Return the matrix as dictionary of keys.
  539. Examples
  540. ========
  541. >>> from sympy import Matrix
  542. >>> M = Matrix.eye(3)
  543. >>> M.todok()
  544. {(0, 0): 1, (1, 1): 1, (2, 2): 1}
  545. """
  546. return self._eval_todok()
  547. @classmethod
  548. def from_dok(cls, rows, cols, dok):
  549. """Create a matrix from a dictionary of keys.
  550. Examples
  551. ========
  552. >>> from sympy import Matrix
  553. >>> d = {(0, 0): 1, (1, 2): 3, (2, 1): 4}
  554. >>> Matrix.from_dok(3, 3, d)
  555. Matrix([
  556. [1, 0, 0],
  557. [0, 0, 3],
  558. [0, 4, 0]])
  559. """
  560. dok = {ij: cls._sympify(val) for ij, val in dok.items()}
  561. return cls._eval_from_dok(rows, cols, dok)
  562. def tolist(self):
  563. """Return the Matrix as a nested Python list.
  564. Examples
  565. ========
  566. >>> from sympy import Matrix, ones
  567. >>> m = Matrix(3, 3, range(9))
  568. >>> m
  569. Matrix([
  570. [0, 1, 2],
  571. [3, 4, 5],
  572. [6, 7, 8]])
  573. >>> m.tolist()
  574. [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
  575. >>> ones(3, 0).tolist()
  576. [[], [], []]
  577. When there are no rows then it will not be possible to tell how
  578. many columns were in the original matrix:
  579. >>> ones(0, 3).tolist()
  580. []
  581. """
  582. if not self.rows:
  583. return []
  584. if not self.cols:
  585. return [[] for i in range(self.rows)]
  586. return self._eval_tolist()
  587. def todod(M):
  588. """Returns matrix as dict of dicts containing non-zero elements of the Matrix
  589. Examples
  590. ========
  591. >>> from sympy import Matrix
  592. >>> A = Matrix([[0, 1],[0, 3]])
  593. >>> A
  594. Matrix([
  595. [0, 1],
  596. [0, 3]])
  597. >>> A.todod()
  598. {0: {1: 1}, 1: {1: 3}}
  599. """
  600. rowsdict = {}
  601. Mlol = M.tolist()
  602. for i, Mi in enumerate(Mlol):
  603. row = {j: Mij for j, Mij in enumerate(Mi) if Mij}
  604. if row:
  605. rowsdict[i] = row
  606. return rowsdict
  607. def vec(self):
  608. """Return the Matrix converted into a one column matrix by stacking columns
  609. Examples
  610. ========
  611. >>> from sympy import Matrix
  612. >>> m=Matrix([[1, 3], [2, 4]])
  613. >>> m
  614. Matrix([
  615. [1, 3],
  616. [2, 4]])
  617. >>> m.vec()
  618. Matrix([
  619. [1],
  620. [2],
  621. [3],
  622. [4]])
  623. See Also
  624. ========
  625. vech
  626. """
  627. return self._eval_vec()
  628. def vech(self, diagonal=True, check_symmetry=True):
  629. """Reshapes the matrix into a column vector by stacking the
  630. elements in the lower triangle.
  631. Parameters
  632. ==========
  633. diagonal : bool, optional
  634. If ``True``, it includes the diagonal elements.
  635. check_symmetry : bool, optional
  636. If ``True``, it checks whether the matrix is symmetric.
  637. Examples
  638. ========
  639. >>> from sympy import Matrix
  640. >>> m=Matrix([[1, 2], [2, 3]])
  641. >>> m
  642. Matrix([
  643. [1, 2],
  644. [2, 3]])
  645. >>> m.vech()
  646. Matrix([
  647. [1],
  648. [2],
  649. [3]])
  650. >>> m.vech(diagonal=False)
  651. Matrix([[2]])
  652. Notes
  653. =====
  654. This should work for symmetric matrices and ``vech`` can
  655. represent symmetric matrices in vector form with less size than
  656. ``vec``.
  657. See Also
  658. ========
  659. vec
  660. """
  661. if not self.is_square:
  662. raise NonSquareMatrixError
  663. if check_symmetry and not self.is_symmetric():
  664. raise ValueError("The matrix is not symmetric.")
  665. return self._eval_vech(diagonal)
  666. @classmethod
  667. def vstack(cls, *args):
  668. """Return a matrix formed by joining args vertically (i.e.
  669. by repeated application of col_join).
  670. Examples
  671. ========
  672. >>> from sympy import Matrix, eye
  673. >>> Matrix.vstack(eye(2), 2*eye(2))
  674. Matrix([
  675. [1, 0],
  676. [0, 1],
  677. [2, 0],
  678. [0, 2]])
  679. """
  680. if len(args) == 0:
  681. return cls._new()
  682. kls = type(args[0])
  683. return reduce(kls.col_join, args)
  684. @classmethod
  685. def _eval_diag(cls, rows, cols, diag_dict):
  686. """diag_dict is a defaultdict containing
  687. all the entries of the diagonal matrix."""
  688. def entry(i, j):
  689. return diag_dict[(i, j)]
  690. return cls._new(rows, cols, entry)
  691. @classmethod
  692. def _eval_eye(cls, rows, cols):
  693. vals = [cls.zero]*(rows*cols)
  694. vals[::cols+1] = [cls.one]*min(rows, cols)
  695. return cls._new(rows, cols, vals, copy=False)
  696. @classmethod
  697. def _eval_jordan_block(cls, size: int, eigenvalue, band='upper'):
  698. if band == 'lower':
  699. def entry(i, j):
  700. if i == j:
  701. return eigenvalue
  702. elif j + 1 == i:
  703. return cls.one
  704. return cls.zero
  705. else:
  706. def entry(i, j):
  707. if i == j:
  708. return eigenvalue
  709. elif i + 1 == j:
  710. return cls.one
  711. return cls.zero
  712. return cls._new(size, size, entry)
  713. @classmethod
  714. def _eval_ones(cls, rows, cols):
  715. def entry(i, j):
  716. return cls.one
  717. return cls._new(rows, cols, entry)
  718. @classmethod
  719. def _eval_zeros(cls, rows, cols):
  720. return cls._new(rows, cols, [cls.zero]*(rows*cols), copy=False)
  721. @classmethod
  722. def _eval_wilkinson(cls, n):
  723. def entry(i, j):
  724. return cls.one if i + 1 == j else cls.zero
  725. D = cls._new(2*n + 1, 2*n + 1, entry)
  726. wminus = cls.diag(list(range(-n, n + 1)), unpack=True) + D + D.T
  727. wplus = abs(cls.diag(list(range(-n, n + 1)), unpack=True)) + D + D.T
  728. return wminus, wplus
  729. @classmethod
  730. def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs):
  731. """Returns a matrix with the specified diagonal.
  732. If matrices are passed, a block-diagonal matrix
  733. is created (i.e. the "direct sum" of the matrices).
  734. kwargs
  735. ======
  736. rows : rows of the resulting matrix; computed if
  737. not given.
  738. cols : columns of the resulting matrix; computed if
  739. not given.
  740. cls : class for the resulting matrix
  741. unpack : bool which, when True (default), unpacks a single
  742. sequence rather than interpreting it as a Matrix.
  743. strict : bool which, when False (default), allows Matrices to
  744. have variable-length rows.
  745. Examples
  746. ========
  747. >>> from sympy import Matrix
  748. >>> Matrix.diag(1, 2, 3)
  749. Matrix([
  750. [1, 0, 0],
  751. [0, 2, 0],
  752. [0, 0, 3]])
  753. The current default is to unpack a single sequence. If this is
  754. not desired, set `unpack=False` and it will be interpreted as
  755. a matrix.
  756. >>> Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
  757. True
  758. When more than one element is passed, each is interpreted as
  759. something to put on the diagonal. Lists are converted to
  760. matrices. Filling of the diagonal always continues from
  761. the bottom right hand corner of the previous item: this
  762. will create a block-diagonal matrix whether the matrices
  763. are square or not.
  764. >>> col = [1, 2, 3]
  765. >>> row = [[4, 5]]
  766. >>> Matrix.diag(col, row)
  767. Matrix([
  768. [1, 0, 0],
  769. [2, 0, 0],
  770. [3, 0, 0],
  771. [0, 4, 5]])
  772. When `unpack` is False, elements within a list need not all be
  773. of the same length. Setting `strict` to True would raise a
  774. ValueError for the following:
  775. >>> Matrix.diag([[1, 2, 3], [4, 5], [6]], unpack=False)
  776. Matrix([
  777. [1, 2, 3],
  778. [4, 5, 0],
  779. [6, 0, 0]])
  780. The type of the returned matrix can be set with the ``cls``
  781. keyword.
  782. >>> from sympy import ImmutableMatrix
  783. >>> from sympy.utilities.misc import func_name
  784. >>> func_name(Matrix.diag(1, cls=ImmutableMatrix))
  785. 'ImmutableDenseMatrix'
  786. A zero dimension matrix can be used to position the start of
  787. the filling at the start of an arbitrary row or column:
  788. >>> from sympy import ones
  789. >>> r2 = ones(0, 2)
  790. >>> Matrix.diag(r2, 1, 2)
  791. Matrix([
  792. [0, 0, 1, 0],
  793. [0, 0, 0, 2]])
  794. See Also
  795. ========
  796. eye
  797. diagonal
  798. .dense.diag
  799. .expressions.blockmatrix.BlockMatrix
  800. .sparsetools.banded
  801. """
  802. from sympy.matrices.matrixbase import MatrixBase
  803. from sympy.matrices.dense import Matrix
  804. from sympy.matrices import SparseMatrix
  805. klass = kwargs.get('cls', kls)
  806. if unpack and len(args) == 1 and is_sequence(args[0]) and \
  807. not isinstance(args[0], MatrixBase):
  808. args = args[0]
  809. # fill a default dict with the diagonal entries
  810. diag_entries = defaultdict(int)
  811. rmax = cmax = 0 # keep track of the biggest index seen
  812. for m in args:
  813. if isinstance(m, list):
  814. if strict:
  815. # if malformed, Matrix will raise an error
  816. _ = Matrix(m)
  817. r, c = _.shape
  818. m = _.tolist()
  819. else:
  820. r, c, smat = SparseMatrix._handle_creation_inputs(m)
  821. for (i, j), _ in smat.items():
  822. diag_entries[(i + rmax, j + cmax)] = _
  823. m = [] # to skip process below
  824. elif hasattr(m, 'shape'): # a Matrix
  825. # convert to list of lists
  826. r, c = m.shape
  827. m = m.tolist()
  828. else: # in this case, we're a single value
  829. diag_entries[(rmax, cmax)] = m
  830. rmax += 1
  831. cmax += 1
  832. continue
  833. # process list of lists
  834. for i, mi in enumerate(m):
  835. for j, _ in enumerate(mi):
  836. diag_entries[(i + rmax, j + cmax)] = _
  837. rmax += r
  838. cmax += c
  839. if rows is None:
  840. rows, cols = cols, rows
  841. if rows is None:
  842. rows, cols = rmax, cmax
  843. else:
  844. cols = rows if cols is None else cols
  845. if rows < rmax or cols < cmax:
  846. raise ValueError(filldedent('''
  847. The constructed matrix is {} x {} but a size of {} x {}
  848. was specified.'''.format(rmax, cmax, rows, cols)))
  849. return klass._eval_diag(rows, cols, diag_entries)
  850. @classmethod
  851. def eye(kls, rows, cols=None, **kwargs):
  852. """Returns an identity matrix.
  853. Parameters
  854. ==========
  855. rows : rows of the matrix
  856. cols : cols of the matrix (if None, cols=rows)
  857. kwargs
  858. ======
  859. cls : class of the returned matrix
  860. """
  861. if cols is None:
  862. cols = rows
  863. if rows < 0 or cols < 0:
  864. raise ValueError("Cannot create a {} x {} matrix. "
  865. "Both dimensions must be positive".format(rows, cols))
  866. klass = kwargs.get('cls', kls)
  867. rows, cols = as_int(rows), as_int(cols)
  868. return klass._eval_eye(rows, cols)
  869. @classmethod
  870. def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs):
  871. """Returns a Jordan block
  872. Parameters
  873. ==========
  874. size : Integer, optional
  875. Specifies the shape of the Jordan block matrix.
  876. eigenvalue : Number or Symbol
  877. Specifies the value for the main diagonal of the matrix.
  878. .. note::
  879. The keyword ``eigenval`` is also specified as an alias
  880. of this keyword, but it is not recommended to use.
  881. We may deprecate the alias in later release.
  882. band : 'upper' or 'lower', optional
  883. Specifies the position of the off-diagonal to put `1` s on.
  884. cls : Matrix, optional
  885. Specifies the matrix class of the output form.
  886. If it is not specified, the class type where the method is
  887. being executed on will be returned.
  888. Returns
  889. =======
  890. Matrix
  891. A Jordan block matrix.
  892. Raises
  893. ======
  894. ValueError
  895. If insufficient arguments are given for matrix size
  896. specification, or no eigenvalue is given.
  897. Examples
  898. ========
  899. Creating a default Jordan block:
  900. >>> from sympy import Matrix
  901. >>> from sympy.abc import x
  902. >>> Matrix.jordan_block(4, x)
  903. Matrix([
  904. [x, 1, 0, 0],
  905. [0, x, 1, 0],
  906. [0, 0, x, 1],
  907. [0, 0, 0, x]])
  908. Creating an alternative Jordan block matrix where `1` is on
  909. lower off-diagonal:
  910. >>> Matrix.jordan_block(4, x, band='lower')
  911. Matrix([
  912. [x, 0, 0, 0],
  913. [1, x, 0, 0],
  914. [0, 1, x, 0],
  915. [0, 0, 1, x]])
  916. Creating a Jordan block with keyword arguments
  917. >>> Matrix.jordan_block(size=4, eigenvalue=x)
  918. Matrix([
  919. [x, 1, 0, 0],
  920. [0, x, 1, 0],
  921. [0, 0, x, 1],
  922. [0, 0, 0, x]])
  923. References
  924. ==========
  925. .. [1] https://en.wikipedia.org/wiki/Jordan_matrix
  926. """
  927. klass = kwargs.pop('cls', kls)
  928. eigenval = kwargs.get('eigenval', None)
  929. if eigenvalue is None and eigenval is None:
  930. raise ValueError("Must supply an eigenvalue")
  931. elif eigenvalue != eigenval and None not in (eigenval, eigenvalue):
  932. raise ValueError(
  933. "Inconsistent values are given: 'eigenval'={}, "
  934. "'eigenvalue'={}".format(eigenval, eigenvalue))
  935. else:
  936. if eigenval is not None:
  937. eigenvalue = eigenval
  938. if size is None:
  939. raise ValueError("Must supply a matrix size")
  940. size = as_int(size)
  941. return klass._eval_jordan_block(size, eigenvalue, band)
  942. @classmethod
  943. def ones(kls, rows, cols=None, **kwargs):
  944. """Returns a matrix of ones.
  945. Parameters
  946. ==========
  947. rows : rows of the matrix
  948. cols : cols of the matrix (if None, cols=rows)
  949. kwargs
  950. ======
  951. cls : class of the returned matrix
  952. """
  953. if cols is None:
  954. cols = rows
  955. klass = kwargs.get('cls', kls)
  956. rows, cols = as_int(rows), as_int(cols)
  957. return klass._eval_ones(rows, cols)
  958. @classmethod
  959. def zeros(kls, rows, cols=None, **kwargs):
  960. """Returns a matrix of zeros.
  961. Parameters
  962. ==========
  963. rows : rows of the matrix
  964. cols : cols of the matrix (if None, cols=rows)
  965. kwargs
  966. ======
  967. cls : class of the returned matrix
  968. """
  969. if cols is None:
  970. cols = rows
  971. if rows < 0 or cols < 0:
  972. raise ValueError("Cannot create a {} x {} matrix. "
  973. "Both dimensions must be positive".format(rows, cols))
  974. klass = kwargs.get('cls', kls)
  975. rows, cols = as_int(rows), as_int(cols)
  976. return klass._eval_zeros(rows, cols)
  977. @classmethod
  978. def companion(kls, poly):
  979. """Returns a companion matrix of a polynomial.
  980. Examples
  981. ========
  982. >>> from sympy import Matrix, Poly, Symbol, symbols
  983. >>> x = Symbol('x')
  984. >>> c0, c1, c2, c3, c4 = symbols('c0:5')
  985. >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x)
  986. >>> Matrix.companion(p)
  987. Matrix([
  988. [0, 0, 0, 0, -c0],
  989. [1, 0, 0, 0, -c1],
  990. [0, 1, 0, 0, -c2],
  991. [0, 0, 1, 0, -c3],
  992. [0, 0, 0, 1, -c4]])
  993. """
  994. poly = kls._sympify(poly)
  995. if not isinstance(poly, Poly):
  996. raise ValueError("{} must be a Poly instance.".format(poly))
  997. if not poly.is_monic:
  998. raise ValueError("{} must be a monic polynomial.".format(poly))
  999. if not poly.is_univariate:
  1000. raise ValueError(
  1001. "{} must be a univariate polynomial.".format(poly))
  1002. size = poly.degree()
  1003. if not size >= 1:
  1004. raise ValueError(
  1005. "{} must have degree not less than 1.".format(poly))
  1006. coeffs = poly.all_coeffs()
  1007. def entry(i, j):
  1008. if j == size - 1:
  1009. return -coeffs[-1 - i]
  1010. elif i == j + 1:
  1011. return kls.one
  1012. return kls.zero
  1013. return kls._new(size, size, entry)
  1014. @classmethod
  1015. def wilkinson(kls, n, **kwargs):
  1016. """Returns two square Wilkinson Matrix of size 2*n + 1
  1017. $W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n)
  1018. Examples
  1019. ========
  1020. >>> from sympy import Matrix
  1021. >>> wminus, wplus = Matrix.wilkinson(3)
  1022. >>> wminus
  1023. Matrix([
  1024. [-3, 1, 0, 0, 0, 0, 0],
  1025. [ 1, -2, 1, 0, 0, 0, 0],
  1026. [ 0, 1, -1, 1, 0, 0, 0],
  1027. [ 0, 0, 1, 0, 1, 0, 0],
  1028. [ 0, 0, 0, 1, 1, 1, 0],
  1029. [ 0, 0, 0, 0, 1, 2, 1],
  1030. [ 0, 0, 0, 0, 0, 1, 3]])
  1031. >>> wplus
  1032. Matrix([
  1033. [3, 1, 0, 0, 0, 0, 0],
  1034. [1, 2, 1, 0, 0, 0, 0],
  1035. [0, 1, 1, 1, 0, 0, 0],
  1036. [0, 0, 1, 0, 1, 0, 0],
  1037. [0, 0, 0, 1, 1, 1, 0],
  1038. [0, 0, 0, 0, 1, 2, 1],
  1039. [0, 0, 0, 0, 0, 1, 3]])
  1040. References
  1041. ==========
  1042. .. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/
  1043. .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp.
  1044. """
  1045. klass = kwargs.get('cls', kls)
  1046. n = as_int(n)
  1047. return klass._eval_wilkinson(n)
  1048. # The RepMatrix subclass uses more efficient sparse implementations of
  1049. # _eval_iter_values and other things.
  1050. def _eval_iter_values(self):
  1051. return (i for i in self if i is not S.Zero)
  1052. def _eval_values(self):
  1053. return list(self.iter_values())
  1054. def _eval_iter_items(self):
  1055. for i in range(self.rows):
  1056. for j in range(self.cols):
  1057. if self[i, j]:
  1058. yield (i, j), self[i, j]
  1059. def _eval_atoms(self, *types):
  1060. values = self.values()
  1061. if len(values) < self.rows * self.cols and isinstance(S.Zero, types):
  1062. s = {S.Zero}
  1063. else:
  1064. s = set()
  1065. return s.union(*[v.atoms(*types) for v in values])
  1066. def _eval_free_symbols(self):
  1067. return set().union(*(i.free_symbols for i in set(self.values())))
  1068. def _eval_has(self, *patterns):
  1069. return any(a.has(*patterns) for a in self.iter_values())
  1070. def _eval_is_symbolic(self):
  1071. return self.has(Symbol)
  1072. # _eval_is_hermitian is called by some general SymPy
  1073. # routines and has a different *args signature. Make
  1074. # sure the names don't clash by adding `_matrix_` in name.
  1075. def _eval_is_matrix_hermitian(self, simpfunc):
  1076. herm = lambda i, j: simpfunc(self[i, j] - self[j, i].adjoint()).is_zero
  1077. return fuzzy_and(herm(i, j) for (i, j), v in self.iter_items())
  1078. def _eval_is_zero_matrix(self):
  1079. return fuzzy_and(v.is_zero for v in self.iter_values())
  1080. def _eval_is_Identity(self) -> FuzzyBool:
  1081. one = self.one
  1082. zero = self.zero
  1083. ident = lambda i, j, v: v is one if i == j else v is zero
  1084. return all(ident(i, j, v) for (i, j), v in self.iter_items())
  1085. def _eval_is_diagonal(self):
  1086. return fuzzy_and(v.is_zero for (i, j), v in self.iter_items() if i != j)
  1087. def _eval_is_lower(self):
  1088. return all(v.is_zero for (i, j), v in self.iter_items() if i < j)
  1089. def _eval_is_upper(self):
  1090. return all(v.is_zero for (i, j), v in self.iter_items() if i > j)
  1091. def _eval_is_lower_hessenberg(self):
  1092. return all(v.is_zero for (i, j), v in self.iter_items() if i + 1 < j)
  1093. def _eval_is_upper_hessenberg(self):
  1094. return all(v.is_zero for (i, j), v in self.iter_items() if i > j + 1)
  1095. def _eval_is_symmetric(self, simpfunc):
  1096. sym = lambda i, j: simpfunc(self[i, j] - self[j, i]).is_zero
  1097. return fuzzy_and(sym(i, j) for (i, j), v in self.iter_items())
  1098. def _eval_is_anti_symmetric(self, simpfunc):
  1099. anti = lambda i, j: simpfunc(self[i, j] + self[j, i]).is_zero
  1100. return fuzzy_and(anti(i, j) for (i, j), v in self.iter_items())
  1101. def _has_positive_diagonals(self):
  1102. diagonal_entries = (self[i, i] for i in range(self.rows))
  1103. return fuzzy_and(x.is_positive for x in diagonal_entries)
  1104. def _has_nonnegative_diagonals(self):
  1105. diagonal_entries = (self[i, i] for i in range(self.rows))
  1106. return fuzzy_and(x.is_nonnegative for x in diagonal_entries)
  1107. def atoms(self, *types):
  1108. """Returns the atoms that form the current object.
  1109. Examples
  1110. ========
  1111. >>> from sympy.abc import x, y
  1112. >>> from sympy import Matrix
  1113. >>> Matrix([[x]])
  1114. Matrix([[x]])
  1115. >>> _.atoms()
  1116. {x}
  1117. >>> Matrix([[x, y], [y, x]])
  1118. Matrix([
  1119. [x, y],
  1120. [y, x]])
  1121. >>> _.atoms()
  1122. {x, y}
  1123. """
  1124. types = tuple(t if isinstance(t, type) else type(t) for t in types)
  1125. if not types:
  1126. types = (Atom,)
  1127. return self._eval_atoms(*types)
  1128. @property
  1129. def free_symbols(self):
  1130. """Returns the free symbols within the matrix.
  1131. Examples
  1132. ========
  1133. >>> from sympy.abc import x
  1134. >>> from sympy import Matrix
  1135. >>> Matrix([[x], [1]]).free_symbols
  1136. {x}
  1137. """
  1138. return self._eval_free_symbols()
  1139. def has(self, *patterns):
  1140. """Test whether any subexpression matches any of the patterns.
  1141. Examples
  1142. ========
  1143. >>> from sympy import Matrix, SparseMatrix, Float
  1144. >>> from sympy.abc import x, y
  1145. >>> A = Matrix(((1, x), (0.2, 3)))
  1146. >>> B = SparseMatrix(((1, x), (0.2, 3)))
  1147. >>> A.has(x)
  1148. True
  1149. >>> A.has(y)
  1150. False
  1151. >>> A.has(Float)
  1152. True
  1153. >>> B.has(x)
  1154. True
  1155. >>> B.has(y)
  1156. False
  1157. >>> B.has(Float)
  1158. True
  1159. """
  1160. return self._eval_has(*patterns)
  1161. def is_anti_symmetric(self, simplify=True):
  1162. """Check if matrix M is an antisymmetric matrix,
  1163. that is, M is a square matrix with all M[i, j] == -M[j, i].
  1164. When ``simplify=True`` (default), the sum M[i, j] + M[j, i] is
  1165. simplified before testing to see if it is zero. By default,
  1166. the SymPy simplify function is used. To use a custom function
  1167. set simplify to a function that accepts a single argument which
  1168. returns a simplified expression. To skip simplification, set
  1169. simplify to False but note that although this will be faster,
  1170. it may induce false negatives.
  1171. Examples
  1172. ========
  1173. >>> from sympy import Matrix, symbols
  1174. >>> m = Matrix(2, 2, [0, 1, -1, 0])
  1175. >>> m
  1176. Matrix([
  1177. [ 0, 1],
  1178. [-1, 0]])
  1179. >>> m.is_anti_symmetric()
  1180. True
  1181. >>> x, y = symbols('x y')
  1182. >>> m = Matrix(2, 3, [0, 0, x, -y, 0, 0])
  1183. >>> m
  1184. Matrix([
  1185. [ 0, 0, x],
  1186. [-y, 0, 0]])
  1187. >>> m.is_anti_symmetric()
  1188. False
  1189. >>> from sympy.abc import x, y
  1190. >>> m = Matrix(3, 3, [0, x**2 + 2*x + 1, y,
  1191. ... -(x + 1)**2, 0, x*y,
  1192. ... -y, -x*y, 0])
  1193. Simplification of matrix elements is done by default so even
  1194. though two elements which should be equal and opposite would not
  1195. pass an equality test, the matrix is still reported as
  1196. anti-symmetric:
  1197. >>> m[0, 1] == -m[1, 0]
  1198. False
  1199. >>> m.is_anti_symmetric()
  1200. True
  1201. If ``simplify=False`` is used for the case when a Matrix is already
  1202. simplified, this will speed things up. Here, we see that without
  1203. simplification the matrix does not appear anti-symmetric:
  1204. >>> print(m.is_anti_symmetric(simplify=False))
  1205. None
  1206. But if the matrix were already expanded, then it would appear
  1207. anti-symmetric and simplification in the is_anti_symmetric routine
  1208. is not needed:
  1209. >>> m = m.expand()
  1210. >>> m.is_anti_symmetric(simplify=False)
  1211. True
  1212. """
  1213. # accept custom simplification
  1214. simpfunc = simplify
  1215. if not isfunction(simplify):
  1216. simpfunc = _utilities_simplify if simplify else lambda x: x
  1217. if not self.is_square:
  1218. return False
  1219. return self._eval_is_anti_symmetric(simpfunc)
  1220. def is_diagonal(self):
  1221. """Check if matrix is diagonal,
  1222. that is matrix in which the entries outside the main diagonal are all zero.
  1223. Examples
  1224. ========
  1225. >>> from sympy import Matrix, diag
  1226. >>> m = Matrix(2, 2, [1, 0, 0, 2])
  1227. >>> m
  1228. Matrix([
  1229. [1, 0],
  1230. [0, 2]])
  1231. >>> m.is_diagonal()
  1232. True
  1233. >>> m = Matrix(2, 2, [1, 1, 0, 2])
  1234. >>> m
  1235. Matrix([
  1236. [1, 1],
  1237. [0, 2]])
  1238. >>> m.is_diagonal()
  1239. False
  1240. >>> m = diag(1, 2, 3)
  1241. >>> m
  1242. Matrix([
  1243. [1, 0, 0],
  1244. [0, 2, 0],
  1245. [0, 0, 3]])
  1246. >>> m.is_diagonal()
  1247. True
  1248. See Also
  1249. ========
  1250. is_lower
  1251. is_upper
  1252. sympy.matrices.matrixbase.MatrixBase.is_diagonalizable
  1253. diagonalize
  1254. """
  1255. return self._eval_is_diagonal()
  1256. @property
  1257. def is_weakly_diagonally_dominant(self):
  1258. r"""Tests if the matrix is row weakly diagonally dominant.
  1259. Explanation
  1260. ===========
  1261. A $n, n$ matrix $A$ is row weakly diagonally dominant if
  1262. .. math::
  1263. \left|A_{i, i}\right| \ge \sum_{j = 0, j \neq i}^{n-1}
  1264. \left|A_{i, j}\right| \quad {\text{for all }}
  1265. i \in \{ 0, ..., n-1 \}
  1266. Examples
  1267. ========
  1268. >>> from sympy import Matrix
  1269. >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
  1270. >>> A.is_weakly_diagonally_dominant
  1271. True
  1272. >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
  1273. >>> A.is_weakly_diagonally_dominant
  1274. False
  1275. >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
  1276. >>> A.is_weakly_diagonally_dominant
  1277. True
  1278. Notes
  1279. =====
  1280. If you want to test whether a matrix is column diagonally
  1281. dominant, you can apply the test after transposing the matrix.
  1282. """
  1283. if not self.is_square:
  1284. return False
  1285. rows, cols = self.shape
  1286. def test_row(i):
  1287. summation = self.zero
  1288. for j in range(cols):
  1289. if i != j:
  1290. summation += Abs(self[i, j])
  1291. return (Abs(self[i, i]) - summation).is_nonnegative
  1292. return fuzzy_and(test_row(i) for i in range(rows))
  1293. @property
  1294. def is_strongly_diagonally_dominant(self):
  1295. r"""Tests if the matrix is row strongly diagonally dominant.
  1296. Explanation
  1297. ===========
  1298. A $n, n$ matrix $A$ is row strongly diagonally dominant if
  1299. .. math::
  1300. \left|A_{i, i}\right| > \sum_{j = 0, j \neq i}^{n-1}
  1301. \left|A_{i, j}\right| \quad {\text{for all }}
  1302. i \in \{ 0, ..., n-1 \}
  1303. Examples
  1304. ========
  1305. >>> from sympy import Matrix
  1306. >>> A = Matrix([[3, -2, 1], [1, -3, 2], [-1, 2, 4]])
  1307. >>> A.is_strongly_diagonally_dominant
  1308. False
  1309. >>> A = Matrix([[-2, 2, 1], [1, 3, 2], [1, -2, 0]])
  1310. >>> A.is_strongly_diagonally_dominant
  1311. False
  1312. >>> A = Matrix([[-4, 2, 1], [1, 6, 2], [1, -2, 5]])
  1313. >>> A.is_strongly_diagonally_dominant
  1314. True
  1315. Notes
  1316. =====
  1317. If you want to test whether a matrix is column diagonally
  1318. dominant, you can apply the test after transposing the matrix.
  1319. """
  1320. if not self.is_square:
  1321. return False
  1322. rows, cols = self.shape
  1323. def test_row(i):
  1324. summation = self.zero
  1325. for j in range(cols):
  1326. if i != j:
  1327. summation += Abs(self[i, j])
  1328. return (Abs(self[i, i]) - summation).is_positive
  1329. return fuzzy_and(test_row(i) for i in range(rows))
  1330. @property
  1331. def is_hermitian(self):
  1332. """Checks if the matrix is Hermitian.
  1333. In a Hermitian matrix element i,j is the complex conjugate of
  1334. element j,i.
  1335. Examples
  1336. ========
  1337. >>> from sympy import Matrix
  1338. >>> from sympy import I
  1339. >>> from sympy.abc import x
  1340. >>> a = Matrix([[1, I], [-I, 1]])
  1341. >>> a
  1342. Matrix([
  1343. [ 1, I],
  1344. [-I, 1]])
  1345. >>> a.is_hermitian
  1346. True
  1347. >>> a[0, 0] = 2*I
  1348. >>> a.is_hermitian
  1349. False
  1350. >>> a[0, 0] = x
  1351. >>> a.is_hermitian
  1352. >>> a[0, 1] = a[1, 0]*I
  1353. >>> a.is_hermitian
  1354. False
  1355. """
  1356. if not self.is_square:
  1357. return False
  1358. return self._eval_is_matrix_hermitian(_utilities_simplify)
  1359. @property
  1360. def is_Identity(self) -> FuzzyBool:
  1361. if not self.is_square:
  1362. return False
  1363. return self._eval_is_Identity()
  1364. @property
  1365. def is_lower_hessenberg(self):
  1366. r"""Checks if the matrix is in the lower-Hessenberg form.
  1367. The lower hessenberg matrix has zero entries
  1368. above the first superdiagonal.
  1369. Examples
  1370. ========
  1371. >>> from sympy import Matrix
  1372. >>> a = Matrix([[1, 2, 0, 0], [5, 2, 3, 0], [3, 4, 3, 7], [5, 6, 1, 1]])
  1373. >>> a
  1374. Matrix([
  1375. [1, 2, 0, 0],
  1376. [5, 2, 3, 0],
  1377. [3, 4, 3, 7],
  1378. [5, 6, 1, 1]])
  1379. >>> a.is_lower_hessenberg
  1380. True
  1381. See Also
  1382. ========
  1383. is_upper_hessenberg
  1384. is_lower
  1385. """
  1386. return self._eval_is_lower_hessenberg()
  1387. @property
  1388. def is_lower(self):
  1389. """Check if matrix is a lower triangular matrix. True can be returned
  1390. even if the matrix is not square.
  1391. Examples
  1392. ========
  1393. >>> from sympy import Matrix
  1394. >>> m = Matrix(2, 2, [1, 0, 0, 1])
  1395. >>> m
  1396. Matrix([
  1397. [1, 0],
  1398. [0, 1]])
  1399. >>> m.is_lower
  1400. True
  1401. >>> m = Matrix(4, 3, [0, 0, 0, 2, 0, 0, 1, 4, 0, 6, 6, 5])
  1402. >>> m
  1403. Matrix([
  1404. [0, 0, 0],
  1405. [2, 0, 0],
  1406. [1, 4, 0],
  1407. [6, 6, 5]])
  1408. >>> m.is_lower
  1409. True
  1410. >>> from sympy.abc import x, y
  1411. >>> m = Matrix(2, 2, [x**2 + y, y**2 + x, 0, x + y])
  1412. >>> m
  1413. Matrix([
  1414. [x**2 + y, x + y**2],
  1415. [ 0, x + y]])
  1416. >>> m.is_lower
  1417. False
  1418. See Also
  1419. ========
  1420. is_upper
  1421. is_diagonal
  1422. is_lower_hessenberg
  1423. """
  1424. return self._eval_is_lower()
  1425. @property
  1426. def is_square(self):
  1427. """Checks if a matrix is square.
  1428. A matrix is square if the number of rows equals the number of columns.
  1429. The empty matrix is square by definition, since the number of rows and
  1430. the number of columns are both zero.
  1431. Examples
  1432. ========
  1433. >>> from sympy import Matrix
  1434. >>> a = Matrix([[1, 2, 3], [4, 5, 6]])
  1435. >>> b = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  1436. >>> c = Matrix([])
  1437. >>> a.is_square
  1438. False
  1439. >>> b.is_square
  1440. True
  1441. >>> c.is_square
  1442. True
  1443. """
  1444. return self.rows == self.cols
  1445. def is_symbolic(self):
  1446. """Checks if any elements contain Symbols.
  1447. Examples
  1448. ========
  1449. >>> from sympy import Matrix
  1450. >>> from sympy.abc import x, y
  1451. >>> M = Matrix([[x, y], [1, 0]])
  1452. >>> M.is_symbolic()
  1453. True
  1454. """
  1455. return self._eval_is_symbolic()
  1456. def is_symmetric(self, simplify=True):
  1457. """Check if matrix is symmetric matrix,
  1458. that is square matrix and is equal to its transpose.
  1459. By default, simplifications occur before testing symmetry.
  1460. They can be skipped using 'simplify=False'; while speeding things a bit,
  1461. this may however induce false negatives.
  1462. Examples
  1463. ========
  1464. >>> from sympy import Matrix
  1465. >>> m = Matrix(2, 2, [0, 1, 1, 2])
  1466. >>> m
  1467. Matrix([
  1468. [0, 1],
  1469. [1, 2]])
  1470. >>> m.is_symmetric()
  1471. True
  1472. >>> m = Matrix(2, 2, [0, 1, 2, 0])
  1473. >>> m
  1474. Matrix([
  1475. [0, 1],
  1476. [2, 0]])
  1477. >>> m.is_symmetric()
  1478. False
  1479. >>> m = Matrix(2, 3, [0, 0, 0, 0, 0, 0])
  1480. >>> m
  1481. Matrix([
  1482. [0, 0, 0],
  1483. [0, 0, 0]])
  1484. >>> m.is_symmetric()
  1485. False
  1486. >>> from sympy.abc import x, y
  1487. >>> m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
  1488. >>> m
  1489. Matrix([
  1490. [ 1, x**2 + 2*x + 1, y],
  1491. [(x + 1)**2, 2, 0],
  1492. [ y, 0, 3]])
  1493. >>> m.is_symmetric()
  1494. True
  1495. If the matrix is already simplified, you may speed-up is_symmetric()
  1496. test by using 'simplify=False'.
  1497. >>> bool(m.is_symmetric(simplify=False))
  1498. False
  1499. >>> m1 = m.expand()
  1500. >>> m1.is_symmetric(simplify=False)
  1501. True
  1502. """
  1503. simpfunc = simplify
  1504. if not isfunction(simplify):
  1505. simpfunc = _utilities_simplify if simplify else lambda x: x
  1506. if not self.is_square:
  1507. return False
  1508. return self._eval_is_symmetric(simpfunc)
  1509. @property
  1510. def is_upper_hessenberg(self):
  1511. """Checks if the matrix is the upper-Hessenberg form.
  1512. The upper hessenberg matrix has zero entries
  1513. below the first subdiagonal.
  1514. Examples
  1515. ========
  1516. >>> from sympy import Matrix
  1517. >>> a = Matrix([[1, 4, 2, 3], [3, 4, 1, 7], [0, 2, 3, 4], [0, 0, 1, 3]])
  1518. >>> a
  1519. Matrix([
  1520. [1, 4, 2, 3],
  1521. [3, 4, 1, 7],
  1522. [0, 2, 3, 4],
  1523. [0, 0, 1, 3]])
  1524. >>> a.is_upper_hessenberg
  1525. True
  1526. See Also
  1527. ========
  1528. is_lower_hessenberg
  1529. is_upper
  1530. """
  1531. return self._eval_is_upper_hessenberg()
  1532. @property
  1533. def is_upper(self):
  1534. """Check if matrix is an upper triangular matrix. True can be returned
  1535. even if the matrix is not square.
  1536. Examples
  1537. ========
  1538. >>> from sympy import Matrix
  1539. >>> m = Matrix(2, 2, [1, 0, 0, 1])
  1540. >>> m
  1541. Matrix([
  1542. [1, 0],
  1543. [0, 1]])
  1544. >>> m.is_upper
  1545. True
  1546. >>> m = Matrix(4, 3, [5, 1, 9, 0, 4, 6, 0, 0, 5, 0, 0, 0])
  1547. >>> m
  1548. Matrix([
  1549. [5, 1, 9],
  1550. [0, 4, 6],
  1551. [0, 0, 5],
  1552. [0, 0, 0]])
  1553. >>> m.is_upper
  1554. True
  1555. >>> m = Matrix(2, 3, [4, 2, 5, 6, 1, 1])
  1556. >>> m
  1557. Matrix([
  1558. [4, 2, 5],
  1559. [6, 1, 1]])
  1560. >>> m.is_upper
  1561. False
  1562. See Also
  1563. ========
  1564. is_lower
  1565. is_diagonal
  1566. is_upper_hessenberg
  1567. """
  1568. return self._eval_is_upper()
  1569. @property
  1570. def is_zero_matrix(self):
  1571. """Checks if a matrix is a zero matrix.
  1572. A matrix is zero if every element is zero. A matrix need not be square
  1573. to be considered zero. The empty matrix is zero by the principle of
  1574. vacuous truth. For a matrix that may or may not be zero (e.g.
  1575. contains a symbol), this will be None
  1576. Examples
  1577. ========
  1578. >>> from sympy import Matrix, zeros
  1579. >>> from sympy.abc import x
  1580. >>> a = Matrix([[0, 0], [0, 0]])
  1581. >>> b = zeros(3, 4)
  1582. >>> c = Matrix([[0, 1], [0, 0]])
  1583. >>> d = Matrix([])
  1584. >>> e = Matrix([[x, 0], [0, 0]])
  1585. >>> a.is_zero_matrix
  1586. True
  1587. >>> b.is_zero_matrix
  1588. True
  1589. >>> c.is_zero_matrix
  1590. False
  1591. >>> d.is_zero_matrix
  1592. True
  1593. >>> e.is_zero_matrix
  1594. """
  1595. return self._eval_is_zero_matrix()
  1596. def values(self):
  1597. """Return non-zero values of self.
  1598. Examples
  1599. ========
  1600. >>> from sympy import Matrix
  1601. >>> m = Matrix([[0, 1], [2, 3]])
  1602. >>> m.values()
  1603. [1, 2, 3]
  1604. See Also
  1605. ========
  1606. iter_values
  1607. tolist
  1608. flat
  1609. """
  1610. return self._eval_values()
  1611. def iter_values(self):
  1612. """
  1613. Iterate over non-zero values of self.
  1614. Examples
  1615. ========
  1616. >>> from sympy import Matrix
  1617. >>> m = Matrix([[0, 1], [2, 3]])
  1618. >>> list(m.iter_values())
  1619. [1, 2, 3]
  1620. See Also
  1621. ========
  1622. values
  1623. """
  1624. return self._eval_iter_values()
  1625. def iter_items(self):
  1626. """Iterate over indices and values of nonzero items.
  1627. Examples
  1628. ========
  1629. >>> from sympy import Matrix
  1630. >>> m = Matrix([[0, 1], [2, 3]])
  1631. >>> list(m.iter_items())
  1632. [((0, 1), 1), ((1, 0), 2), ((1, 1), 3)]
  1633. See Also
  1634. ========
  1635. iter_values
  1636. todok
  1637. """
  1638. return self._eval_iter_items()
  1639. def _eval_adjoint(self):
  1640. return self.transpose().applyfunc(lambda x: x.adjoint())
  1641. def _eval_applyfunc(self, f):
  1642. cols = self.cols
  1643. size = self.rows*self.cols
  1644. dok = self.todok()
  1645. valmap = {v: f(v) for v in dok.values()}
  1646. if len(dok) < size and ((fzero := f(S.Zero)) is not S.Zero):
  1647. out_flat = [fzero]*size
  1648. for (i, j), v in dok.items():
  1649. out_flat[i*cols + j] = valmap[v]
  1650. out = self._new(self.rows, self.cols, out_flat)
  1651. else:
  1652. fdok = {ij: valmap[v] for ij, v in dok.items()}
  1653. out = self.from_dok(self.rows, self.cols, fdok)
  1654. return out
  1655. def _eval_as_real_imag(self): # type: ignore
  1656. return (self.applyfunc(re), self.applyfunc(im))
  1657. def _eval_conjugate(self):
  1658. return self.applyfunc(lambda x: x.conjugate())
  1659. def _eval_permute_cols(self, perm):
  1660. # apply the permutation to a list
  1661. mapping = list(perm)
  1662. def entry(i, j):
  1663. return self[i, mapping[j]]
  1664. return self._new(self.rows, self.cols, entry)
  1665. def _eval_permute_rows(self, perm):
  1666. # apply the permutation to a list
  1667. mapping = list(perm)
  1668. def entry(i, j):
  1669. return self[mapping[i], j]
  1670. return self._new(self.rows, self.cols, entry)
  1671. def _eval_trace(self):
  1672. return sum(self[i, i] for i in range(self.rows))
  1673. def _eval_transpose(self):
  1674. return self._new(self.cols, self.rows, lambda i, j: self[j, i])
  1675. def adjoint(self):
  1676. """Conjugate transpose or Hermitian conjugation."""
  1677. return self._eval_adjoint()
  1678. def applyfunc(self, f):
  1679. """Apply a function to each element of the matrix.
  1680. Examples
  1681. ========
  1682. >>> from sympy import Matrix
  1683. >>> m = Matrix(2, 2, lambda i, j: i*2+j)
  1684. >>> m
  1685. Matrix([
  1686. [0, 1],
  1687. [2, 3]])
  1688. >>> m.applyfunc(lambda i: 2*i)
  1689. Matrix([
  1690. [0, 2],
  1691. [4, 6]])
  1692. """
  1693. if not callable(f):
  1694. raise TypeError("`f` must be callable.")
  1695. return self._eval_applyfunc(f)
  1696. def as_real_imag(self, deep=True, **hints):
  1697. """Returns a tuple containing the (real, imaginary) part of matrix."""
  1698. # XXX: Ignoring deep and hints...
  1699. return self._eval_as_real_imag()
  1700. def conjugate(self):
  1701. """Return the by-element conjugation.
  1702. Examples
  1703. ========
  1704. >>> from sympy import SparseMatrix, I
  1705. >>> a = SparseMatrix(((1, 2 + I), (3, 4), (I, -I)))
  1706. >>> a
  1707. Matrix([
  1708. [1, 2 + I],
  1709. [3, 4],
  1710. [I, -I]])
  1711. >>> a.C
  1712. Matrix([
  1713. [ 1, 2 - I],
  1714. [ 3, 4],
  1715. [-I, I]])
  1716. See Also
  1717. ========
  1718. transpose: Matrix transposition
  1719. H: Hermite conjugation
  1720. sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation
  1721. """
  1722. return self._eval_conjugate()
  1723. def doit(self, **hints):
  1724. return self.applyfunc(lambda x: x.doit(**hints))
  1725. def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
  1726. """Apply evalf() to each element of self."""
  1727. options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict,
  1728. 'quad':quad, 'verbose':verbose}
  1729. return self.applyfunc(lambda i: i.evalf(n, **options))
  1730. def expand(self, deep=True, modulus=None, power_base=True, power_exp=True,
  1731. mul=True, log=True, multinomial=True, basic=True, **hints):
  1732. """Apply core.function.expand to each entry of the matrix.
  1733. Examples
  1734. ========
  1735. >>> from sympy.abc import x
  1736. >>> from sympy import Matrix
  1737. >>> Matrix(1, 1, [x*(x+1)])
  1738. Matrix([[x*(x + 1)]])
  1739. >>> _.expand()
  1740. Matrix([[x**2 + x]])
  1741. """
  1742. return self.applyfunc(lambda x: x.expand(
  1743. deep, modulus, power_base, power_exp, mul, log, multinomial, basic,
  1744. **hints))
  1745. @property
  1746. def H(self):
  1747. """Return Hermite conjugate.
  1748. Examples
  1749. ========
  1750. >>> from sympy import Matrix, I
  1751. >>> m = Matrix((0, 1 + I, 2, 3))
  1752. >>> m
  1753. Matrix([
  1754. [ 0],
  1755. [1 + I],
  1756. [ 2],
  1757. [ 3]])
  1758. >>> m.H
  1759. Matrix([[0, 1 - I, 2, 3]])
  1760. See Also
  1761. ========
  1762. conjugate: By-element conjugation
  1763. sympy.matrices.matrixbase.MatrixBase.D: Dirac conjugation
  1764. """
  1765. return self.adjoint()
  1766. def permute(self, perm, orientation='rows', direction='forward'):
  1767. r"""Permute the rows or columns of a matrix by the given list of
  1768. swaps.
  1769. Parameters
  1770. ==========
  1771. perm : Permutation, list, or list of lists
  1772. A representation for the permutation.
  1773. If it is ``Permutation``, it is used directly with some
  1774. resizing with respect to the matrix size.
  1775. If it is specified as list of lists,
  1776. (e.g., ``[[0, 1], [0, 2]]``), then the permutation is formed
  1777. from applying the product of cycles. The direction how the
  1778. cyclic product is applied is described in below.
  1779. If it is specified as a list, the list should represent
  1780. an array form of a permutation. (e.g., ``[1, 2, 0]``) which
  1781. would would form the swapping function
  1782. `0 \mapsto 1, 1 \mapsto 2, 2\mapsto 0`.
  1783. orientation : 'rows', 'cols'
  1784. A flag to control whether to permute the rows or the columns
  1785. direction : 'forward', 'backward'
  1786. A flag to control whether to apply the permutations from
  1787. the start of the list first, or from the back of the list
  1788. first.
  1789. For example, if the permutation specification is
  1790. ``[[0, 1], [0, 2]]``,
  1791. If the flag is set to ``'forward'``, the cycle would be
  1792. formed as `0 \mapsto 2, 2 \mapsto 1, 1 \mapsto 0`.
  1793. If the flag is set to ``'backward'``, the cycle would be
  1794. formed as `0 \mapsto 1, 1 \mapsto 2, 2 \mapsto 0`.
  1795. If the argument ``perm`` is not in a form of list of lists,
  1796. this flag takes no effect.
  1797. Examples
  1798. ========
  1799. >>> from sympy import eye
  1800. >>> M = eye(3)
  1801. >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='forward')
  1802. Matrix([
  1803. [0, 0, 1],
  1804. [1, 0, 0],
  1805. [0, 1, 0]])
  1806. >>> from sympy import eye
  1807. >>> M = eye(3)
  1808. >>> M.permute([[0, 1], [0, 2]], orientation='rows', direction='backward')
  1809. Matrix([
  1810. [0, 1, 0],
  1811. [0, 0, 1],
  1812. [1, 0, 0]])
  1813. Notes
  1814. =====
  1815. If a bijective function
  1816. `\sigma : \mathbb{N}_0 \rightarrow \mathbb{N}_0` denotes the
  1817. permutation.
  1818. If the matrix `A` is the matrix to permute, represented as
  1819. a horizontal or a vertical stack of vectors:
  1820. .. math::
  1821. A =
  1822. \begin{bmatrix}
  1823. a_0 \\ a_1 \\ \vdots \\ a_{n-1}
  1824. \end{bmatrix} =
  1825. \begin{bmatrix}
  1826. \alpha_0 & \alpha_1 & \cdots & \alpha_{n-1}
  1827. \end{bmatrix}
  1828. If the matrix `B` is the result, the permutation of matrix rows
  1829. is defined as:
  1830. .. math::
  1831. B := \begin{bmatrix}
  1832. a_{\sigma(0)} \\ a_{\sigma(1)} \\ \vdots \\ a_{\sigma(n-1)}
  1833. \end{bmatrix}
  1834. And the permutation of matrix columns is defined as:
  1835. .. math::
  1836. B := \begin{bmatrix}
  1837. \alpha_{\sigma(0)} & \alpha_{\sigma(1)} &
  1838. \cdots & \alpha_{\sigma(n-1)}
  1839. \end{bmatrix}
  1840. """
  1841. from sympy.combinatorics import Permutation
  1842. # allow british variants and `columns`
  1843. if direction == 'forwards':
  1844. direction = 'forward'
  1845. if direction == 'backwards':
  1846. direction = 'backward'
  1847. if orientation == 'columns':
  1848. orientation = 'cols'
  1849. if direction not in ('forward', 'backward'):
  1850. raise TypeError("direction='{}' is an invalid kwarg. "
  1851. "Try 'forward' or 'backward'".format(direction))
  1852. if orientation not in ('rows', 'cols'):
  1853. raise TypeError("orientation='{}' is an invalid kwarg. "
  1854. "Try 'rows' or 'cols'".format(orientation))
  1855. if not isinstance(perm, (Permutation, Iterable)):
  1856. raise ValueError(
  1857. "{} must be a list, a list of lists, "
  1858. "or a SymPy permutation object.".format(perm))
  1859. # ensure all swaps are in range
  1860. max_index = self.rows if orientation == 'rows' else self.cols
  1861. if not all(0 <= t <= max_index for t in flatten(list(perm))):
  1862. raise IndexError("`swap` indices out of range.")
  1863. if perm and not isinstance(perm, Permutation) and \
  1864. isinstance(perm[0], Iterable):
  1865. if direction == 'forward':
  1866. perm = list(reversed(perm))
  1867. perm = Permutation(perm, size=max_index+1)
  1868. else:
  1869. perm = Permutation(perm, size=max_index+1)
  1870. if orientation == 'rows':
  1871. return self._eval_permute_rows(perm)
  1872. if orientation == 'cols':
  1873. return self._eval_permute_cols(perm)
  1874. def permute_cols(self, swaps, direction='forward'):
  1875. """Alias for
  1876. ``self.permute(swaps, orientation='cols', direction=direction)``
  1877. See Also
  1878. ========
  1879. permute
  1880. """
  1881. return self.permute(swaps, orientation='cols', direction=direction)
  1882. def permute_rows(self, swaps, direction='forward'):
  1883. """Alias for
  1884. ``self.permute(swaps, orientation='rows', direction=direction)``
  1885. See Also
  1886. ========
  1887. permute
  1888. """
  1889. return self.permute(swaps, orientation='rows', direction=direction)
  1890. def refine(self, assumptions=True):
  1891. """Apply refine to each element of the matrix.
  1892. Examples
  1893. ========
  1894. >>> from sympy import Symbol, Matrix, Abs, sqrt, Q
  1895. >>> x = Symbol('x')
  1896. >>> Matrix([[Abs(x)**2, sqrt(x**2)],[sqrt(x**2), Abs(x)**2]])
  1897. Matrix([
  1898. [ Abs(x)**2, sqrt(x**2)],
  1899. [sqrt(x**2), Abs(x)**2]])
  1900. >>> _.refine(Q.real(x))
  1901. Matrix([
  1902. [ x**2, Abs(x)],
  1903. [Abs(x), x**2]])
  1904. """
  1905. return self.applyfunc(lambda x: refine(x, assumptions))
  1906. def replace(self, F, G, map=False, simultaneous=True, exact=None):
  1907. """Replaces Function F in Matrix entries with Function G.
  1908. Examples
  1909. ========
  1910. >>> from sympy import symbols, Function, Matrix
  1911. >>> F, G = symbols('F, G', cls=Function)
  1912. >>> M = Matrix(2, 2, lambda i, j: F(i+j)) ; M
  1913. Matrix([
  1914. [F(0), F(1)],
  1915. [F(1), F(2)]])
  1916. >>> N = M.replace(F,G)
  1917. >>> N
  1918. Matrix([
  1919. [G(0), G(1)],
  1920. [G(1), G(2)]])
  1921. """
  1922. kwargs = {'map': map, 'simultaneous': simultaneous, 'exact': exact}
  1923. if map:
  1924. d = {}
  1925. def func(eij):
  1926. eij, dij = eij.replace(F, G, **kwargs)
  1927. d.update(dij)
  1928. return eij
  1929. M = self.applyfunc(func)
  1930. return M, d
  1931. else:
  1932. return self.applyfunc(lambda i: i.replace(F, G, **kwargs))
  1933. def rot90(self, k=1):
  1934. """Rotates Matrix by 90 degrees
  1935. Parameters
  1936. ==========
  1937. k : int
  1938. Specifies how many times the matrix is rotated by 90 degrees
  1939. (clockwise when positive, counter-clockwise when negative).
  1940. Examples
  1941. ========
  1942. >>> from sympy import Matrix, symbols
  1943. >>> A = Matrix(2, 2, symbols('a:d'))
  1944. >>> A
  1945. Matrix([
  1946. [a, b],
  1947. [c, d]])
  1948. Rotating the matrix clockwise one time:
  1949. >>> A.rot90(1)
  1950. Matrix([
  1951. [c, a],
  1952. [d, b]])
  1953. Rotating the matrix anticlockwise two times:
  1954. >>> A.rot90(-2)
  1955. Matrix([
  1956. [d, c],
  1957. [b, a]])
  1958. """
  1959. mod = k%4
  1960. if mod == 0:
  1961. return self
  1962. if mod == 1:
  1963. return self[::-1, ::].T
  1964. if mod == 2:
  1965. return self[::-1, ::-1]
  1966. if mod == 3:
  1967. return self[::, ::-1].T
  1968. def simplify(self, **kwargs):
  1969. """Apply simplify to each element of the matrix.
  1970. Examples
  1971. ========
  1972. >>> from sympy.abc import x, y
  1973. >>> from sympy import SparseMatrix, sin, cos
  1974. >>> SparseMatrix(1, 1, [x*sin(y)**2 + x*cos(y)**2])
  1975. Matrix([[x*sin(y)**2 + x*cos(y)**2]])
  1976. >>> _.simplify()
  1977. Matrix([[x]])
  1978. """
  1979. return self.applyfunc(lambda x: x.simplify(**kwargs))
  1980. def subs(self, *args, **kwargs): # should mirror core.basic.subs
  1981. """Return a new matrix with subs applied to each entry.
  1982. Examples
  1983. ========
  1984. >>> from sympy.abc import x, y
  1985. >>> from sympy import SparseMatrix, Matrix
  1986. >>> SparseMatrix(1, 1, [x])
  1987. Matrix([[x]])
  1988. >>> _.subs(x, y)
  1989. Matrix([[y]])
  1990. >>> Matrix(_).subs(y, x)
  1991. Matrix([[x]])
  1992. """
  1993. if len(args) == 1 and not isinstance(args[0], (dict, set)) and iter(args[0]) and not is_sequence(args[0]):
  1994. args = (list(args[0]),)
  1995. return self.applyfunc(lambda x: x.subs(*args, **kwargs))
  1996. def trace(self):
  1997. """
  1998. Returns the trace of a square matrix i.e. the sum of the
  1999. diagonal elements.
  2000. Examples
  2001. ========
  2002. >>> from sympy import Matrix
  2003. >>> A = Matrix(2, 2, [1, 2, 3, 4])
  2004. >>> A.trace()
  2005. 5
  2006. """
  2007. if self.rows != self.cols:
  2008. raise NonSquareMatrixError()
  2009. return self._eval_trace()
  2010. def transpose(self):
  2011. """
  2012. Returns the transpose of the matrix.
  2013. Examples
  2014. ========
  2015. >>> from sympy import Matrix
  2016. >>> A = Matrix(2, 2, [1, 2, 3, 4])
  2017. >>> A.transpose()
  2018. Matrix([
  2019. [1, 3],
  2020. [2, 4]])
  2021. >>> from sympy import Matrix, I
  2022. >>> m=Matrix(((1, 2+I), (3, 4)))
  2023. >>> m
  2024. Matrix([
  2025. [1, 2 + I],
  2026. [3, 4]])
  2027. >>> m.transpose()
  2028. Matrix([
  2029. [ 1, 3],
  2030. [2 + I, 4]])
  2031. >>> m.T == m.transpose()
  2032. True
  2033. See Also
  2034. ========
  2035. conjugate: By-element conjugation
  2036. """
  2037. return self._eval_transpose()
  2038. @property
  2039. def T(self):
  2040. '''Matrix transposition'''
  2041. return self.transpose()
  2042. @property
  2043. def C(self):
  2044. '''By-element conjugation'''
  2045. return self.conjugate()
  2046. def n(self, *args, **kwargs):
  2047. """Apply evalf() to each element of self."""
  2048. return self.evalf(*args, **kwargs)
  2049. def xreplace(self, rule): # should mirror core.basic.xreplace
  2050. """Return a new matrix with xreplace applied to each entry.
  2051. Examples
  2052. ========
  2053. >>> from sympy.abc import x, y
  2054. >>> from sympy import SparseMatrix, Matrix
  2055. >>> SparseMatrix(1, 1, [x])
  2056. Matrix([[x]])
  2057. >>> _.xreplace({x: y})
  2058. Matrix([[y]])
  2059. >>> Matrix(_).xreplace({y: x})
  2060. Matrix([[x]])
  2061. """
  2062. return self.applyfunc(lambda x: x.xreplace(rule))
  2063. def _eval_simplify(self, **kwargs):
  2064. # XXX: We can't use self.simplify here as mutable subclasses will
  2065. # override simplify and have it return None
  2066. return self.applyfunc(lambda x: x.simplify(**kwargs))
  2067. def _eval_trigsimp(self, **opts):
  2068. from sympy.simplify.trigsimp import trigsimp
  2069. return self.applyfunc(lambda x: trigsimp(x, **opts))
  2070. def upper_triangular(self, k=0):
  2071. """Return the elements on and above the kth diagonal of a matrix.
  2072. If k is not specified then simply returns upper-triangular portion
  2073. of a matrix
  2074. Examples
  2075. ========
  2076. >>> from sympy import ones
  2077. >>> A = ones(4)
  2078. >>> A.upper_triangular()
  2079. Matrix([
  2080. [1, 1, 1, 1],
  2081. [0, 1, 1, 1],
  2082. [0, 0, 1, 1],
  2083. [0, 0, 0, 1]])
  2084. >>> A.upper_triangular(2)
  2085. Matrix([
  2086. [0, 0, 1, 1],
  2087. [0, 0, 0, 1],
  2088. [0, 0, 0, 0],
  2089. [0, 0, 0, 0]])
  2090. >>> A.upper_triangular(-1)
  2091. Matrix([
  2092. [1, 1, 1, 1],
  2093. [1, 1, 1, 1],
  2094. [0, 1, 1, 1],
  2095. [0, 0, 1, 1]])
  2096. """
  2097. def entry(i, j):
  2098. return self[i, j] if i + k <= j else self.zero
  2099. return self._new(self.rows, self.cols, entry)
  2100. def lower_triangular(self, k=0):
  2101. """Return the elements on and below the kth diagonal of a matrix.
  2102. If k is not specified then simply returns lower-triangular portion
  2103. of a matrix
  2104. Examples
  2105. ========
  2106. >>> from sympy import ones
  2107. >>> A = ones(4)
  2108. >>> A.lower_triangular()
  2109. Matrix([
  2110. [1, 0, 0, 0],
  2111. [1, 1, 0, 0],
  2112. [1, 1, 1, 0],
  2113. [1, 1, 1, 1]])
  2114. >>> A.lower_triangular(-2)
  2115. Matrix([
  2116. [0, 0, 0, 0],
  2117. [0, 0, 0, 0],
  2118. [1, 0, 0, 0],
  2119. [1, 1, 0, 0]])
  2120. >>> A.lower_triangular(1)
  2121. Matrix([
  2122. [1, 1, 0, 0],
  2123. [1, 1, 1, 0],
  2124. [1, 1, 1, 1],
  2125. [1, 1, 1, 1]])
  2126. """
  2127. def entry(i, j):
  2128. return self[i, j] if i + k >= j else self.zero
  2129. return self._new(self.rows, self.cols, entry)
  2130. def _eval_Abs(self):
  2131. return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j]))
  2132. def _eval_add(self, other):
  2133. return self._new(self.rows, self.cols,
  2134. lambda i, j: self[i, j] + other[i, j])
  2135. def _eval_matrix_mul(self, other):
  2136. def entry(i, j):
  2137. vec = [self[i,k]*other[k,j] for k in range(self.cols)]
  2138. try:
  2139. return Add(*vec)
  2140. except (TypeError, SympifyError):
  2141. # Some matrices don't work with `sum` or `Add`
  2142. # They don't work with `sum` because `sum` tries to add `0`
  2143. # Fall back to a safe way to multiply if the `Add` fails.
  2144. return reduce(lambda a, b: a + b, vec)
  2145. return self._new(self.rows, other.cols, entry)
  2146. def _eval_matrix_mul_elementwise(self, other):
  2147. return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j])
  2148. def _eval_matrix_rmul(self, other):
  2149. def entry(i, j):
  2150. return sum(other[i,k]*self[k,j] for k in range(other.cols))
  2151. return self._new(other.rows, self.cols, entry)
  2152. def _eval_pow_by_recursion(self, num):
  2153. if num == 1:
  2154. return self
  2155. if num % 2 == 1:
  2156. a, b = self, self._eval_pow_by_recursion(num - 1)
  2157. else:
  2158. a = b = self._eval_pow_by_recursion(num // 2)
  2159. return a.multiply(b)
  2160. def _eval_pow_by_cayley(self, exp):
  2161. from sympy.discrete.recurrences import linrec_coeffs
  2162. row = self.shape[0]
  2163. p = self.charpoly()
  2164. coeffs = (-p).all_coeffs()[1:]
  2165. coeffs = linrec_coeffs(coeffs, exp)
  2166. new_mat = self.eye(row)
  2167. ans = self.zeros(row)
  2168. for i in range(row):
  2169. ans += coeffs[i]*new_mat
  2170. new_mat *= self
  2171. return ans
  2172. def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None):
  2173. if prevsimp is None:
  2174. prevsimp = [True]*len(self)
  2175. if num == 1:
  2176. return self
  2177. if num % 2 == 1:
  2178. a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1,
  2179. prevsimp=prevsimp)
  2180. else:
  2181. a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2,
  2182. prevsimp=prevsimp)
  2183. m = a.multiply(b, dotprodsimp=False)
  2184. lenm = len(m)
  2185. elems = [None]*lenm
  2186. for i in range(lenm):
  2187. if prevsimp[i]:
  2188. elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True)
  2189. else:
  2190. elems[i] = m[i]
  2191. return m._new(m.rows, m.cols, elems)
  2192. def _eval_scalar_mul(self, other):
  2193. return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other)
  2194. def _eval_scalar_rmul(self, other):
  2195. return self._new(self.rows, self.cols, lambda i, j: other*self[i,j])
  2196. def _eval_Mod(self, other):
  2197. return self._new(self.rows, self.cols, lambda i, j: Mod(self[i, j], other))
  2198. # Python arithmetic functions
  2199. def __abs__(self):
  2200. """Returns a new matrix with entry-wise absolute values."""
  2201. return self._eval_Abs()
  2202. @call_highest_priority('__radd__')
  2203. def __add__(self, other):
  2204. """Return self + other, raising ShapeError if shapes do not match."""
  2205. other, T = _coerce_operand(self, other)
  2206. if T != "is_matrix":
  2207. return NotImplemented
  2208. if self.shape != other.shape:
  2209. raise ShapeError(f"Matrix size mismatch: {self.shape} + {other.shape}.")
  2210. # Unify matrix types
  2211. a, b = self, other
  2212. if a.__class__ != classof(a, b):
  2213. b, a = a, b
  2214. return a._eval_add(b)
  2215. @call_highest_priority('__rtruediv__')
  2216. def __truediv__(self, other):
  2217. return self * (self.one / other)
  2218. @call_highest_priority('__rmatmul__')
  2219. def __matmul__(self, other):
  2220. self, other, T = _unify_with_other(self, other)
  2221. if T != "is_matrix":
  2222. return NotImplemented
  2223. return self.__mul__(other)
  2224. def __mod__(self, other):
  2225. return self.applyfunc(lambda x: x % other)
  2226. @call_highest_priority('__rmul__')
  2227. def __mul__(self, other):
  2228. """Return self*other where other is either a scalar or a matrix
  2229. of compatible dimensions.
  2230. Examples
  2231. ========
  2232. >>> from sympy import Matrix
  2233. >>> A = Matrix([[1, 2, 3], [4, 5, 6]])
  2234. >>> 2*A == A*2 == Matrix([[2, 4, 6], [8, 10, 12]])
  2235. True
  2236. >>> B = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  2237. >>> A*B
  2238. Matrix([
  2239. [30, 36, 42],
  2240. [66, 81, 96]])
  2241. >>> B*A
  2242. Traceback (most recent call last):
  2243. ...
  2244. ShapeError: Matrices size mismatch.
  2245. >>>
  2246. See Also
  2247. ========
  2248. matrix_multiply_elementwise
  2249. """
  2250. return self.multiply(other)
  2251. def multiply(self, other, dotprodsimp=None):
  2252. """Same as __mul__() but with optional simplification.
  2253. Parameters
  2254. ==========
  2255. dotprodsimp : bool, optional
  2256. Specifies whether intermediate term algebraic simplification is used
  2257. during matrix multiplications to control expression blowup and thus
  2258. speed up calculation. Default is off.
  2259. """
  2260. isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
  2261. self, other, T = _unify_with_other(self, other)
  2262. if T == "possible_scalar":
  2263. try:
  2264. return self._eval_scalar_mul(other)
  2265. except TypeError:
  2266. return NotImplemented
  2267. elif T == "is_matrix":
  2268. if self.shape[1] != other.shape[0]:
  2269. raise ShapeError(f"Matrix size mismatch: {self.shape} * {other.shape}.")
  2270. m = self._eval_matrix_mul(other)
  2271. if isimpbool:
  2272. m = m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
  2273. return m
  2274. else:
  2275. return NotImplemented
  2276. def multiply_elementwise(self, other):
  2277. """Return the Hadamard product (elementwise product) of A and B
  2278. Examples
  2279. ========
  2280. >>> from sympy import Matrix
  2281. >>> A = Matrix([[0, 1, 2], [3, 4, 5]])
  2282. >>> B = Matrix([[1, 10, 100], [100, 10, 1]])
  2283. >>> A.multiply_elementwise(B)
  2284. Matrix([
  2285. [ 0, 10, 200],
  2286. [300, 40, 5]])
  2287. See Also
  2288. ========
  2289. sympy.matrices.matrixbase.MatrixBase.cross
  2290. sympy.matrices.matrixbase.MatrixBase.dot
  2291. multiply
  2292. """
  2293. if self.shape != other.shape:
  2294. raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape))
  2295. return self._eval_matrix_mul_elementwise(other)
  2296. def __neg__(self):
  2297. return self._eval_scalar_mul(-1)
  2298. @call_highest_priority('__rpow__')
  2299. def __pow__(self, exp):
  2300. """Return self**exp a scalar or symbol."""
  2301. return self.pow(exp)
  2302. def pow(self, exp, method=None):
  2303. r"""Return self**exp a scalar or symbol.
  2304. Parameters
  2305. ==========
  2306. method : multiply, mulsimp, jordan, cayley
  2307. If multiply then it returns exponentiation using recursion.
  2308. If jordan then Jordan form exponentiation will be used.
  2309. If cayley then the exponentiation is done using Cayley-Hamilton
  2310. theorem.
  2311. If mulsimp then the exponentiation is done using recursion
  2312. with dotprodsimp. This specifies whether intermediate term
  2313. algebraic simplification is used during naive matrix power to
  2314. control expression blowup and thus speed up calculation.
  2315. If None, then it heuristically decides which method to use.
  2316. """
  2317. if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']:
  2318. raise TypeError('No such method')
  2319. if self.rows != self.cols:
  2320. raise NonSquareMatrixError()
  2321. a = self
  2322. jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None)
  2323. exp = sympify(exp)
  2324. if exp.is_zero:
  2325. return a._new(a.rows, a.cols, lambda i, j: int(i == j))
  2326. if exp == 1:
  2327. return a
  2328. diagonal = getattr(a, 'is_diagonal', None)
  2329. if diagonal is not None and diagonal():
  2330. return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0)
  2331. if exp.is_Number and exp % 1 == 0:
  2332. if a.rows == 1:
  2333. return a._new([[a[0]**exp]])
  2334. if exp < 0:
  2335. exp = -exp
  2336. a = a.inv()
  2337. # When certain conditions are met,
  2338. # Jordan block algorithm is faster than
  2339. # computation by recursion.
  2340. if method == 'jordan':
  2341. try:
  2342. return jordan_pow(exp)
  2343. except MatrixError:
  2344. if method == 'jordan':
  2345. raise
  2346. elif method == 'cayley':
  2347. if not exp.is_Number or exp % 1 != 0:
  2348. raise ValueError("cayley method is only valid for integer powers")
  2349. return a._eval_pow_by_cayley(exp)
  2350. elif method == "mulsimp":
  2351. if not exp.is_Number or exp % 1 != 0:
  2352. raise ValueError("mulsimp method is only valid for integer powers")
  2353. return a._eval_pow_by_recursion_dotprodsimp(exp)
  2354. elif method == "multiply":
  2355. if not exp.is_Number or exp % 1 != 0:
  2356. raise ValueError("multiply method is only valid for integer powers")
  2357. return a._eval_pow_by_recursion(exp)
  2358. elif method is None and exp.is_Number and exp % 1 == 0:
  2359. if exp.is_Float:
  2360. exp = Integer(exp)
  2361. # Decide heuristically which method to apply
  2362. if a.rows == 2 and exp > 100000:
  2363. return jordan_pow(exp)
  2364. elif _get_intermediate_simp_bool(True, None):
  2365. return a._eval_pow_by_recursion_dotprodsimp(exp)
  2366. elif exp > 10000:
  2367. return a._eval_pow_by_cayley(exp)
  2368. else:
  2369. return a._eval_pow_by_recursion(exp)
  2370. if jordan_pow:
  2371. try:
  2372. return jordan_pow(exp)
  2373. except NonInvertibleMatrixError:
  2374. # Raised by jordan_pow on zero determinant matrix unless exp is
  2375. # definitely known to be a non-negative integer.
  2376. # Here we raise if n is definitely not a non-negative integer
  2377. # but otherwise we can leave this as an unevaluated MatPow.
  2378. if exp.is_integer is False or exp.is_nonnegative is False:
  2379. raise
  2380. from sympy.matrices.expressions import MatPow
  2381. return MatPow(a, exp)
  2382. @call_highest_priority('__add__')
  2383. def __radd__(self, other):
  2384. return self.__add__(other)
  2385. @call_highest_priority('__matmul__')
  2386. def __rmatmul__(self, other):
  2387. self, other, T = _unify_with_other(self, other)
  2388. if T != "is_matrix":
  2389. return NotImplemented
  2390. return self.__rmul__(other)
  2391. @call_highest_priority('__mul__')
  2392. def __rmul__(self, other):
  2393. return self.rmultiply(other)
  2394. def rmultiply(self, other, dotprodsimp=None):
  2395. """Same as __rmul__() but with optional simplification.
  2396. Parameters
  2397. ==========
  2398. dotprodsimp : bool, optional
  2399. Specifies whether intermediate term algebraic simplification is used
  2400. during matrix multiplications to control expression blowup and thus
  2401. speed up calculation. Default is off.
  2402. """
  2403. isimpbool = _get_intermediate_simp_bool(False, dotprodsimp)
  2404. self, other, T = _unify_with_other(self, other)
  2405. if T == "possible_scalar":
  2406. try:
  2407. return self._eval_scalar_rmul(other)
  2408. except TypeError:
  2409. return NotImplemented
  2410. elif T == "is_matrix":
  2411. if self.shape[0] != other.shape[1]:
  2412. raise ShapeError("Matrix size mismatch.")
  2413. m = self._eval_matrix_rmul(other)
  2414. if isimpbool:
  2415. return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m])
  2416. return m
  2417. else:
  2418. return NotImplemented
  2419. @call_highest_priority('__sub__')
  2420. def __rsub__(self, a):
  2421. return (-self) + a
  2422. @call_highest_priority('__rsub__')
  2423. def __sub__(self, a):
  2424. return self + (-a)
  2425. def _eval_det_bareiss(self, iszerofunc=_is_zero_after_expand_mul):
  2426. return _det_bareiss(self, iszerofunc=iszerofunc)
  2427. def _eval_det_berkowitz(self):
  2428. return _det_berkowitz(self)
  2429. def _eval_det_lu(self, iszerofunc=_iszero, simpfunc=None):
  2430. return _det_LU(self, iszerofunc=iszerofunc, simpfunc=simpfunc)
  2431. def _eval_det_bird(self):
  2432. return _det_bird(self)
  2433. def _eval_det_laplace(self):
  2434. return _det_laplace(self)
  2435. def _eval_determinant(self): # for expressions.determinant.Determinant
  2436. return _det(self)
  2437. def adjugate(self, method="berkowitz"):
  2438. return _adjugate(self, method=method)
  2439. def charpoly(self, x='lambda', simplify=_utilities_simplify):
  2440. return _charpoly(self, x=x, simplify=simplify)
  2441. def cofactor(self, i, j, method="berkowitz"):
  2442. return _cofactor(self, i, j, method=method)
  2443. def cofactor_matrix(self, method="berkowitz"):
  2444. return _cofactor_matrix(self, method=method)
  2445. def det(self, method="bareiss", iszerofunc=None):
  2446. return _det(self, method=method, iszerofunc=iszerofunc)
  2447. def per(self):
  2448. return _per(self)
  2449. def minor(self, i, j, method="berkowitz"):
  2450. return _minor(self, i, j, method=method)
  2451. def minor_submatrix(self, i, j):
  2452. return _minor_submatrix(self, i, j)
  2453. _find_reasonable_pivot.__doc__ = _find_reasonable_pivot.__doc__
  2454. _find_reasonable_pivot_naive.__doc__ = _find_reasonable_pivot_naive.__doc__
  2455. _eval_det_bareiss.__doc__ = _det_bareiss.__doc__
  2456. _eval_det_berkowitz.__doc__ = _det_berkowitz.__doc__
  2457. _eval_det_bird.__doc__ = _det_bird.__doc__
  2458. _eval_det_laplace.__doc__ = _det_laplace.__doc__
  2459. _eval_det_lu.__doc__ = _det_LU.__doc__
  2460. _eval_determinant.__doc__ = _det.__doc__
  2461. adjugate.__doc__ = _adjugate.__doc__
  2462. charpoly.__doc__ = _charpoly.__doc__
  2463. cofactor.__doc__ = _cofactor.__doc__
  2464. cofactor_matrix.__doc__ = _cofactor_matrix.__doc__
  2465. det.__doc__ = _det.__doc__
  2466. per.__doc__ = _per.__doc__
  2467. minor.__doc__ = _minor.__doc__
  2468. minor_submatrix.__doc__ = _minor_submatrix.__doc__
  2469. def echelon_form(self, iszerofunc=_iszero, simplify=False, with_pivots=False):
  2470. return _echelon_form(self, iszerofunc=iszerofunc, simplify=simplify,
  2471. with_pivots=with_pivots)
  2472. @property
  2473. def is_echelon(self):
  2474. return _is_echelon(self)
  2475. def rank(self, iszerofunc=_iszero, simplify=False):
  2476. return _rank(self, iszerofunc=iszerofunc, simplify=simplify)
  2477. def rref_rhs(self, rhs):
  2478. """Return reduced row-echelon form of matrix, matrix showing
  2479. rhs after reduction steps. ``rhs`` must have the same number
  2480. of rows as ``self``.
  2481. Examples
  2482. ========
  2483. >>> from sympy import Matrix, symbols
  2484. >>> r1, r2 = symbols('r1 r2')
  2485. >>> Matrix([[1, 1], [2, 1]]).rref_rhs(Matrix([r1, r2]))
  2486. (Matrix([
  2487. [1, 0],
  2488. [0, 1]]), Matrix([
  2489. [ -r1 + r2],
  2490. [2*r1 - r2]]))
  2491. """
  2492. r, _ = _rref(self.hstack(self, self.eye(self.rows), rhs))
  2493. return r[:, :self.cols], r[:, -rhs.cols:]
  2494. def rref(self, iszerofunc=_iszero, simplify=False, pivots=True,
  2495. normalize_last=True):
  2496. return _rref(self, iszerofunc=iszerofunc, simplify=simplify,
  2497. pivots=pivots, normalize_last=normalize_last)
  2498. echelon_form.__doc__ = _echelon_form.__doc__
  2499. is_echelon.__doc__ = _is_echelon.__doc__
  2500. rank.__doc__ = _rank.__doc__
  2501. rref.__doc__ = _rref.__doc__
  2502. def _normalize_op_args(self, op, col, k, col1, col2, error_str="col"):
  2503. """Validate the arguments for a row/column operation. ``error_str``
  2504. can be one of "row" or "col" depending on the arguments being parsed."""
  2505. if op not in ["n->kn", "n<->m", "n->n+km"]:
  2506. raise ValueError("Unknown {} operation '{}'. Valid col operations "
  2507. "are 'n->kn', 'n<->m', 'n->n+km'".format(error_str, op))
  2508. # define self_col according to error_str
  2509. self_cols = self.cols if error_str == 'col' else self.rows
  2510. # normalize and validate the arguments
  2511. if op == "n->kn":
  2512. col = col if col is not None else col1
  2513. if col is None or k is None:
  2514. raise ValueError("For a {0} operation 'n->kn' you must provide the "
  2515. "kwargs `{0}` and `k`".format(error_str))
  2516. if not 0 <= col < self_cols:
  2517. raise ValueError("This matrix does not have a {} '{}'".format(error_str, col))
  2518. elif op == "n<->m":
  2519. # we need two cols to swap. It does not matter
  2520. # how they were specified, so gather them together and
  2521. # remove `None`
  2522. cols = {col, k, col1, col2}.difference([None])
  2523. if len(cols) > 2:
  2524. # maybe the user left `k` by mistake?
  2525. cols = {col, col1, col2}.difference([None])
  2526. if len(cols) != 2:
  2527. raise ValueError("For a {0} operation 'n<->m' you must provide the "
  2528. "kwargs `{0}1` and `{0}2`".format(error_str))
  2529. col1, col2 = cols
  2530. if not 0 <= col1 < self_cols:
  2531. raise ValueError("This matrix does not have a {} '{}'".format(error_str, col1))
  2532. if not 0 <= col2 < self_cols:
  2533. raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2))
  2534. elif op == "n->n+km":
  2535. col = col1 if col is None else col
  2536. col2 = col1 if col2 is None else col2
  2537. if col is None or col2 is None or k is None:
  2538. raise ValueError("For a {0} operation 'n->n+km' you must provide the "
  2539. "kwargs `{0}`, `k`, and `{0}2`".format(error_str))
  2540. if col == col2:
  2541. raise ValueError("For a {0} operation 'n->n+km' `{0}` and `{0}2` must "
  2542. "be different.".format(error_str))
  2543. if not 0 <= col < self_cols:
  2544. raise ValueError("This matrix does not have a {} '{}'".format(error_str, col))
  2545. if not 0 <= col2 < self_cols:
  2546. raise ValueError("This matrix does not have a {} '{}'".format(error_str, col2))
  2547. else:
  2548. raise ValueError('invalid operation %s' % repr(op))
  2549. return op, col, k, col1, col2
  2550. def _eval_col_op_multiply_col_by_const(self, col, k):
  2551. def entry(i, j):
  2552. if j == col:
  2553. return k * self[i, j]
  2554. return self[i, j]
  2555. return self._new(self.rows, self.cols, entry)
  2556. def _eval_col_op_swap(self, col1, col2):
  2557. def entry(i, j):
  2558. if j == col1:
  2559. return self[i, col2]
  2560. elif j == col2:
  2561. return self[i, col1]
  2562. return self[i, j]
  2563. return self._new(self.rows, self.cols, entry)
  2564. def _eval_col_op_add_multiple_to_other_col(self, col, k, col2):
  2565. def entry(i, j):
  2566. if j == col:
  2567. return self[i, j] + k * self[i, col2]
  2568. return self[i, j]
  2569. return self._new(self.rows, self.cols, entry)
  2570. def _eval_row_op_swap(self, row1, row2):
  2571. def entry(i, j):
  2572. if i == row1:
  2573. return self[row2, j]
  2574. elif i == row2:
  2575. return self[row1, j]
  2576. return self[i, j]
  2577. return self._new(self.rows, self.cols, entry)
  2578. def _eval_row_op_multiply_row_by_const(self, row, k):
  2579. def entry(i, j):
  2580. if i == row:
  2581. return k * self[i, j]
  2582. return self[i, j]
  2583. return self._new(self.rows, self.cols, entry)
  2584. def _eval_row_op_add_multiple_to_other_row(self, row, k, row2):
  2585. def entry(i, j):
  2586. if i == row:
  2587. return self[i, j] + k * self[row2, j]
  2588. return self[i, j]
  2589. return self._new(self.rows, self.cols, entry)
  2590. def elementary_col_op(self, op="n->kn", col=None, k=None, col1=None, col2=None):
  2591. """Performs the elementary column operation `op`.
  2592. `op` may be one of
  2593. * ``"n->kn"`` (column n goes to k*n)
  2594. * ``"n<->m"`` (swap column n and column m)
  2595. * ``"n->n+km"`` (column n goes to column n + k*column m)
  2596. Parameters
  2597. ==========
  2598. op : string; the elementary row operation
  2599. col : the column to apply the column operation
  2600. k : the multiple to apply in the column operation
  2601. col1 : one column of a column swap
  2602. col2 : second column of a column swap or column "m" in the column operation
  2603. "n->n+km"
  2604. """
  2605. op, col, k, col1, col2 = self._normalize_op_args(op, col, k, col1, col2, "col")
  2606. # now that we've validated, we're all good to dispatch
  2607. if op == "n->kn":
  2608. return self._eval_col_op_multiply_col_by_const(col, k)
  2609. if op == "n<->m":
  2610. return self._eval_col_op_swap(col1, col2)
  2611. if op == "n->n+km":
  2612. return self._eval_col_op_add_multiple_to_other_col(col, k, col2)
  2613. def elementary_row_op(self, op="n->kn", row=None, k=None, row1=None, row2=None):
  2614. """Performs the elementary row operation `op`.
  2615. `op` may be one of
  2616. * ``"n->kn"`` (row n goes to k*n)
  2617. * ``"n<->m"`` (swap row n and row m)
  2618. * ``"n->n+km"`` (row n goes to row n + k*row m)
  2619. Parameters
  2620. ==========
  2621. op : string; the elementary row operation
  2622. row : the row to apply the row operation
  2623. k : the multiple to apply in the row operation
  2624. row1 : one row of a row swap
  2625. row2 : second row of a row swap or row "m" in the row operation
  2626. "n->n+km"
  2627. """
  2628. op, row, k, row1, row2 = self._normalize_op_args(op, row, k, row1, row2, "row")
  2629. # now that we've validated, we're all good to dispatch
  2630. if op == "n->kn":
  2631. return self._eval_row_op_multiply_row_by_const(row, k)
  2632. if op == "n<->m":
  2633. return self._eval_row_op_swap(row1, row2)
  2634. if op == "n->n+km":
  2635. return self._eval_row_op_add_multiple_to_other_row(row, k, row2)
  2636. def columnspace(self, simplify=False):
  2637. return _columnspace(self, simplify=simplify)
  2638. def nullspace(self, simplify=False, iszerofunc=_iszero):
  2639. return _nullspace(self, simplify=simplify, iszerofunc=iszerofunc)
  2640. def rowspace(self, simplify=False):
  2641. return _rowspace(self, simplify=simplify)
  2642. # This is a classmethod but is converted to such later in order to allow
  2643. # assignment of __doc__ since that does not work for already wrapped
  2644. # classmethods in Python 3.6.
  2645. def orthogonalize(cls, *vecs, **kwargs):
  2646. return _orthogonalize(cls, *vecs, **kwargs)
  2647. columnspace.__doc__ = _columnspace.__doc__
  2648. nullspace.__doc__ = _nullspace.__doc__
  2649. rowspace.__doc__ = _rowspace.__doc__
  2650. orthogonalize.__doc__ = _orthogonalize.__doc__
  2651. orthogonalize = classmethod(orthogonalize) # type:ignore
  2652. def eigenvals(self, error_when_incomplete=True, **flags):
  2653. return _eigenvals(self, error_when_incomplete=error_when_incomplete, **flags)
  2654. def eigenvects(self, error_when_incomplete=True, iszerofunc=_iszero, **flags):
  2655. return _eigenvects(self, error_when_incomplete=error_when_incomplete,
  2656. iszerofunc=iszerofunc, **flags)
  2657. def is_diagonalizable(self, reals_only=False, **kwargs):
  2658. return _is_diagonalizable(self, reals_only=reals_only, **kwargs)
  2659. def diagonalize(self, reals_only=False, sort=False, normalize=False):
  2660. return _diagonalize(self, reals_only=reals_only, sort=sort,
  2661. normalize=normalize)
  2662. def bidiagonalize(self, upper=True):
  2663. return _bidiagonalize(self, upper=upper)
  2664. def bidiagonal_decomposition(self, upper=True):
  2665. return _bidiagonal_decomposition(self, upper=upper)
  2666. @property
  2667. def is_positive_definite(self):
  2668. return _is_positive_definite(self)
  2669. @property
  2670. def is_positive_semidefinite(self):
  2671. return _is_positive_semidefinite(self)
  2672. @property
  2673. def is_negative_definite(self):
  2674. return _is_negative_definite(self)
  2675. @property
  2676. def is_negative_semidefinite(self):
  2677. return _is_negative_semidefinite(self)
  2678. @property
  2679. def is_indefinite(self):
  2680. return _is_indefinite(self)
  2681. def jordan_form(self, calc_transform=True, **kwargs):
  2682. return _jordan_form(self, calc_transform=calc_transform, **kwargs)
  2683. def left_eigenvects(self, **flags):
  2684. return _left_eigenvects(self, **flags)
  2685. def singular_values(self):
  2686. return _singular_values(self)
  2687. eigenvals.__doc__ = _eigenvals.__doc__
  2688. eigenvects.__doc__ = _eigenvects.__doc__
  2689. is_diagonalizable.__doc__ = _is_diagonalizable.__doc__
  2690. diagonalize.__doc__ = _diagonalize.__doc__
  2691. is_positive_definite.__doc__ = _is_positive_definite.__doc__
  2692. is_positive_semidefinite.__doc__ = _is_positive_semidefinite.__doc__
  2693. is_negative_definite.__doc__ = _is_negative_definite.__doc__
  2694. is_negative_semidefinite.__doc__ = _is_negative_semidefinite.__doc__
  2695. is_indefinite.__doc__ = _is_indefinite.__doc__
  2696. jordan_form.__doc__ = _jordan_form.__doc__
  2697. left_eigenvects.__doc__ = _left_eigenvects.__doc__
  2698. singular_values.__doc__ = _singular_values.__doc__
  2699. bidiagonalize.__doc__ = _bidiagonalize.__doc__
  2700. bidiagonal_decomposition.__doc__ = _bidiagonal_decomposition.__doc__
  2701. def diff(self, *args, evaluate=True, **kwargs):
  2702. """Calculate the derivative of each element in the matrix.
  2703. Examples
  2704. ========
  2705. >>> from sympy import Matrix
  2706. >>> from sympy.abc import x, y
  2707. >>> M = Matrix([[x, y], [1, 0]])
  2708. >>> M.diff(x)
  2709. Matrix([
  2710. [1, 0],
  2711. [0, 0]])
  2712. See Also
  2713. ========
  2714. integrate
  2715. limit
  2716. """
  2717. # XXX this should be handled here rather than in Derivative
  2718. from sympy.tensor.array.array_derivatives import ArrayDerivative
  2719. deriv = ArrayDerivative(self, *args, evaluate=evaluate)
  2720. # XXX This can rather changed to always return immutable matrix
  2721. if not isinstance(self, Basic) and evaluate:
  2722. return deriv.as_mutable()
  2723. return deriv
  2724. def _eval_derivative(self, arg):
  2725. return self.applyfunc(lambda x: x.diff(arg))
  2726. def integrate(self, *args, **kwargs):
  2727. """Integrate each element of the matrix. ``args`` will
  2728. be passed to the ``integrate`` function.
  2729. Examples
  2730. ========
  2731. >>> from sympy import Matrix
  2732. >>> from sympy.abc import x, y
  2733. >>> M = Matrix([[x, y], [1, 0]])
  2734. >>> M.integrate((x, ))
  2735. Matrix([
  2736. [x**2/2, x*y],
  2737. [ x, 0]])
  2738. >>> M.integrate((x, 0, 2))
  2739. Matrix([
  2740. [2, 2*y],
  2741. [2, 0]])
  2742. See Also
  2743. ========
  2744. limit
  2745. diff
  2746. """
  2747. return self.applyfunc(lambda x: x.integrate(*args, **kwargs))
  2748. def jacobian(self, X):
  2749. """Calculates the Jacobian matrix (derivative of a vector-valued function).
  2750. Parameters
  2751. ==========
  2752. ``self`` : vector of expressions representing functions f_i(x_1, ..., x_n).
  2753. X : set of x_i's in order, it can be a list or a Matrix
  2754. Both ``self`` and X can be a row or a column matrix in any order
  2755. (i.e., jacobian() should always work).
  2756. Examples
  2757. ========
  2758. >>> from sympy import sin, cos, Matrix
  2759. >>> from sympy.abc import rho, phi
  2760. >>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
  2761. >>> Y = Matrix([rho, phi])
  2762. >>> X.jacobian(Y)
  2763. Matrix([
  2764. [cos(phi), -rho*sin(phi)],
  2765. [sin(phi), rho*cos(phi)],
  2766. [ 2*rho, 0]])
  2767. >>> X = Matrix([rho*cos(phi), rho*sin(phi)])
  2768. >>> X.jacobian(Y)
  2769. Matrix([
  2770. [cos(phi), -rho*sin(phi)],
  2771. [sin(phi), rho*cos(phi)]])
  2772. See Also
  2773. ========
  2774. hessian
  2775. wronskian
  2776. """
  2777. from sympy.matrices.matrixbase import MatrixBase
  2778. if not isinstance(X, MatrixBase):
  2779. X = self._new(X)
  2780. # Both X and ``self`` can be a row or a column matrix, so we need to make
  2781. # sure all valid combinations work, but everything else fails:
  2782. if self.shape[0] == 1:
  2783. m = self.shape[1]
  2784. elif self.shape[1] == 1:
  2785. m = self.shape[0]
  2786. else:
  2787. raise TypeError("``self`` must be a row or a column matrix")
  2788. if X.shape[0] == 1:
  2789. n = X.shape[1]
  2790. elif X.shape[1] == 1:
  2791. n = X.shape[0]
  2792. else:
  2793. raise TypeError("X must be a row or a column matrix")
  2794. # m is the number of functions and n is the number of variables
  2795. # computing the Jacobian is now easy:
  2796. return self._new(m, n, lambda j, i: self[j].diff(X[i]))
  2797. def limit(self, *args):
  2798. """Calculate the limit of each element in the matrix.
  2799. ``args`` will be passed to the ``limit`` function.
  2800. Examples
  2801. ========
  2802. >>> from sympy import Matrix
  2803. >>> from sympy.abc import x, y
  2804. >>> M = Matrix([[x, y], [1, 0]])
  2805. >>> M.limit(x, 2)
  2806. Matrix([
  2807. [2, y],
  2808. [1, 0]])
  2809. See Also
  2810. ========
  2811. integrate
  2812. diff
  2813. """
  2814. return self.applyfunc(lambda x: x.limit(*args))
  2815. def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_utilities_simplify):
  2816. return self.charpoly(x=x)
  2817. def berkowitz_det(self):
  2818. """Computes determinant using Berkowitz method.
  2819. See Also
  2820. ========
  2821. det
  2822. """
  2823. return self.det(method='berkowitz')
  2824. def berkowitz_eigenvals(self, **flags):
  2825. """Computes eigenvalues of a Matrix using Berkowitz method."""
  2826. return self.eigenvals(**flags)
  2827. def berkowitz_minors(self):
  2828. """Computes principal minors using Berkowitz method."""
  2829. sign, minors = self.one, []
  2830. for poly in self.berkowitz():
  2831. minors.append(sign * poly[-1])
  2832. sign = -sign
  2833. return tuple(minors)
  2834. def berkowitz(self):
  2835. from sympy.matrices import zeros
  2836. berk = ((1,),)
  2837. if not self:
  2838. return berk
  2839. if not self.is_square:
  2840. raise NonSquareMatrixError()
  2841. A, N = self, self.rows
  2842. transforms = [0] * (N - 1)
  2843. for n in range(N, 1, -1):
  2844. T, k = zeros(n + 1, n), n - 1
  2845. R, C = -A[k, :k], A[:k, k]
  2846. A, a = A[:k, :k], -A[k, k]
  2847. items = [C]
  2848. for i in range(0, n - 2):
  2849. items.append(A * items[i])
  2850. for i, B in enumerate(items):
  2851. items[i] = (R * B)[0, 0]
  2852. items = [self.one, a] + items
  2853. for i in range(n):
  2854. T[i:, i] = items[:n - i + 1]
  2855. transforms[k - 1] = T
  2856. polys = [self._new([self.one, -A[0, 0]])]
  2857. for i, T in enumerate(transforms):
  2858. polys.append(T * polys[i])
  2859. return berk + tuple(map(tuple, polys))
  2860. def cofactorMatrix(self, method="berkowitz"):
  2861. return self.cofactor_matrix(method=method)
  2862. def det_bareis(self):
  2863. return _det_bareiss(self)
  2864. def det_LU_decomposition(self):
  2865. """Compute matrix determinant using LU decomposition.
  2866. Note that this method fails if the LU decomposition itself
  2867. fails. In particular, if the matrix has no inverse this method
  2868. will fail.
  2869. TODO: Implement algorithm for sparse matrices (SFF),
  2870. http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.
  2871. See Also
  2872. ========
  2873. det
  2874. berkowitz_det
  2875. """
  2876. return self.det(method='lu')
  2877. def jordan_cell(self, eigenval, n):
  2878. return self.jordan_block(size=n, eigenvalue=eigenval)
  2879. def jordan_cells(self, calc_transformation=True):
  2880. P, J = self.jordan_form()
  2881. return P, J.get_diag_blocks()
  2882. def minorEntry(self, i, j, method="berkowitz"):
  2883. return self.minor(i, j, method=method)
  2884. def minorMatrix(self, i, j):
  2885. return self.minor_submatrix(i, j)
  2886. def permuteBkwd(self, perm):
  2887. """Permute the rows of the matrix with the given permutation in reverse."""
  2888. return self.permute_rows(perm, direction='backward')
  2889. def permuteFwd(self, perm):
  2890. """Permute the rows of the matrix with the given permutation."""
  2891. return self.permute_rows(perm, direction='forward')
  2892. @property
  2893. def kind(self) -> MatrixKind:
  2894. elem_kinds = {e.kind for e in self.flat()}
  2895. if len(elem_kinds) == 1:
  2896. elemkind, = elem_kinds
  2897. else:
  2898. elemkind = UndefinedKind
  2899. return MatrixKind(elemkind)
  2900. def flat(self):
  2901. """
  2902. Returns a flat list of all elements in the matrix.
  2903. Examples
  2904. ========
  2905. >>> from sympy import Matrix
  2906. >>> m = Matrix([[0, 2], [3, 4]])
  2907. >>> m.flat()
  2908. [0, 2, 3, 4]
  2909. See Also
  2910. ========
  2911. tolist
  2912. values
  2913. """
  2914. return [self[i, j] for i in range(self.rows) for j in range(self.cols)]
  2915. def __array__(self, dtype=object, copy=None):
  2916. if copy is not None and not copy:
  2917. raise TypeError("Cannot implement copy=False when converting Matrix to ndarray")
  2918. from .dense import matrix2numpy
  2919. return matrix2numpy(self, dtype=dtype)
  2920. def __len__(self):
  2921. """Return the number of elements of ``self``.
  2922. Implemented mainly so bool(Matrix()) == False.
  2923. """
  2924. return self.rows * self.cols
  2925. def _matrix_pow_by_jordan_blocks(self, num):
  2926. from sympy.matrices import diag, MutableMatrix
  2927. def jordan_cell_power(jc, n):
  2928. N = jc.shape[0]
  2929. l = jc[0,0]
  2930. if l.is_zero:
  2931. if N == 1 and n.is_nonnegative:
  2932. jc[0,0] = l**n
  2933. elif not (n.is_integer and n.is_nonnegative):
  2934. raise NonInvertibleMatrixError("Non-invertible matrix can only be raised to a nonnegative integer")
  2935. else:
  2936. for i in range(N):
  2937. jc[0,i] = KroneckerDelta(i, n)
  2938. else:
  2939. for i in range(N):
  2940. bn = binomial(n, i)
  2941. if isinstance(bn, binomial):
  2942. bn = bn._eval_expand_func()
  2943. jc[0,i] = l**(n-i)*bn
  2944. for i in range(N):
  2945. for j in range(1, N-i):
  2946. jc[j,i+j] = jc [j-1,i+j-1]
  2947. P, J = self.jordan_form()
  2948. jordan_cells = J.get_diag_blocks()
  2949. # Make sure jordan_cells matrices are mutable:
  2950. jordan_cells = [MutableMatrix(j) for j in jordan_cells]
  2951. for j in jordan_cells:
  2952. jordan_cell_power(j, num)
  2953. return self._new(P.multiply(diag(*jordan_cells))
  2954. .multiply(P.inv()))
  2955. def __str__(self):
  2956. if S.Zero in self.shape:
  2957. return 'Matrix(%s, %s, [])' % (self.rows, self.cols)
  2958. return "Matrix(%s)" % str(self.tolist())
  2959. def _format_str(self, printer=None):
  2960. if not printer:
  2961. printer = StrPrinter()
  2962. # Handle zero dimensions:
  2963. if S.Zero in self.shape:
  2964. return 'Matrix(%s, %s, [])' % (self.rows, self.cols)
  2965. if self.rows == 1:
  2966. return "Matrix([%s])" % self.table(printer, rowsep=',\n')
  2967. return "Matrix([\n%s])" % self.table(printer, rowsep=',\n')
  2968. @classmethod
  2969. def irregular(cls, ntop, *matrices, **kwargs):
  2970. """Return a matrix filled by the given matrices which
  2971. are listed in order of appearance from left to right, top to
  2972. bottom as they first appear in the matrix. They must fill the
  2973. matrix completely.
  2974. Examples
  2975. ========
  2976. >>> from sympy import ones, Matrix
  2977. >>> Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3,
  2978. ... ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7)
  2979. Matrix([
  2980. [1, 2, 2, 2, 3, 3],
  2981. [1, 2, 2, 2, 3, 3],
  2982. [4, 2, 2, 2, 5, 5],
  2983. [6, 6, 7, 7, 5, 5]])
  2984. """
  2985. ntop = as_int(ntop)
  2986. # make sure we are working with explicit matrices
  2987. b = [i.as_explicit() if hasattr(i, 'as_explicit') else i
  2988. for i in matrices]
  2989. q = list(range(len(b)))
  2990. dat = [i.rows for i in b]
  2991. active = [q.pop(0) for _ in range(ntop)]
  2992. cols = sum(b[i].cols for i in active)
  2993. rows = []
  2994. while any(dat):
  2995. r = []
  2996. for a, j in enumerate(active):
  2997. r.extend(b[j][-dat[j], :])
  2998. dat[j] -= 1
  2999. if dat[j] == 0 and q:
  3000. active[a] = q.pop(0)
  3001. if len(r) != cols:
  3002. raise ValueError(filldedent('''
  3003. Matrices provided do not appear to fill
  3004. the space completely.'''))
  3005. rows.append(r)
  3006. return cls._new(rows)
  3007. @classmethod
  3008. def _handle_ndarray(cls, arg):
  3009. # NumPy array or matrix or some other object that implements
  3010. # __array__. So let's first use this method to get a
  3011. # numpy.array() and then make a Python list out of it.
  3012. arr = arg.__array__()
  3013. if len(arr.shape) == 2:
  3014. rows, cols = arr.shape[0], arr.shape[1]
  3015. flat_list = [cls._sympify(i) for i in arr.ravel()]
  3016. return rows, cols, flat_list
  3017. elif len(arr.shape) == 1:
  3018. flat_list = [cls._sympify(i) for i in arr]
  3019. return arr.shape[0], 1, flat_list
  3020. else:
  3021. raise NotImplementedError(
  3022. "SymPy supports just 1D and 2D matrices")
  3023. @classmethod
  3024. def _handle_creation_inputs(cls, *args, **kwargs):
  3025. """Return the number of rows, cols and flat matrix elements.
  3026. Examples
  3027. ========
  3028. >>> from sympy import Matrix, I
  3029. Matrix can be constructed as follows:
  3030. * from a nested list of iterables
  3031. >>> Matrix( ((1, 2+I), (3, 4)) )
  3032. Matrix([
  3033. [1, 2 + I],
  3034. [3, 4]])
  3035. * from un-nested iterable (interpreted as a column)
  3036. >>> Matrix( [1, 2] )
  3037. Matrix([
  3038. [1],
  3039. [2]])
  3040. * from un-nested iterable with dimensions
  3041. >>> Matrix(1, 2, [1, 2] )
  3042. Matrix([[1, 2]])
  3043. * from no arguments (a 0 x 0 matrix)
  3044. >>> Matrix()
  3045. Matrix(0, 0, [])
  3046. * from a rule
  3047. >>> Matrix(2, 2, lambda i, j: i/(j + 1) )
  3048. Matrix([
  3049. [0, 0],
  3050. [1, 1/2]])
  3051. See Also
  3052. ========
  3053. irregular - filling a matrix with irregular blocks
  3054. """
  3055. from sympy.matrices import SparseMatrix
  3056. from sympy.matrices.expressions.matexpr import MatrixSymbol
  3057. from sympy.matrices.expressions.blockmatrix import BlockMatrix
  3058. flat_list = None
  3059. if len(args) == 1:
  3060. # Matrix(SparseMatrix(...))
  3061. if isinstance(args[0], SparseMatrix):
  3062. return args[0].rows, args[0].cols, flatten(args[0].tolist())
  3063. # Matrix(Matrix(...))
  3064. elif isinstance(args[0], MatrixBase):
  3065. return args[0].rows, args[0].cols, args[0].flat()
  3066. # Matrix(MatrixSymbol('X', 2, 2))
  3067. elif isinstance(args[0], Basic) and args[0].is_Matrix:
  3068. return args[0].rows, args[0].cols, args[0].as_explicit().flat()
  3069. elif isinstance(args[0], mp.matrix):
  3070. M = args[0]
  3071. flat_list = [cls._sympify(x) for x in M]
  3072. return M.rows, M.cols, flat_list
  3073. # Matrix(numpy.ones((2, 2)))
  3074. elif hasattr(args[0], "__array__"):
  3075. return cls._handle_ndarray(args[0])
  3076. # Matrix([1, 2, 3]) or Matrix([[1, 2], [3, 4]])
  3077. elif is_sequence(args[0]) \
  3078. and not isinstance(args[0], DeferredVector):
  3079. dat = list(args[0])
  3080. ismat = lambda i: isinstance(i, MatrixBase) and (
  3081. evaluate or isinstance(i, (BlockMatrix, MatrixSymbol)))
  3082. raw = lambda i: is_sequence(i) and not ismat(i)
  3083. evaluate = kwargs.get('evaluate', True)
  3084. if evaluate:
  3085. def make_explicit(x):
  3086. """make Block and Symbol explicit"""
  3087. if isinstance(x, BlockMatrix):
  3088. return x.as_explicit()
  3089. elif isinstance(x, MatrixSymbol) and all(_.is_Integer for _ in x.shape):
  3090. return x.as_explicit()
  3091. else:
  3092. return x
  3093. def make_explicit_row(row):
  3094. # Could be list or could be list of lists
  3095. if isinstance(row, (list, tuple)):
  3096. return [make_explicit(x) for x in row]
  3097. else:
  3098. return make_explicit(row)
  3099. if isinstance(dat, (list, tuple)):
  3100. dat = [make_explicit_row(row) for row in dat]
  3101. if len(dat) == 0:
  3102. rows = cols = 0
  3103. flat_list = []
  3104. elif all(raw(i) for i in dat) and len(dat[0]) == 0:
  3105. if not all(len(i) == 0 for i in dat):
  3106. raise ValueError('mismatched dimensions')
  3107. rows = len(dat)
  3108. cols = 0
  3109. flat_list = []
  3110. elif not any(raw(i) or ismat(i) for i in dat):
  3111. # a column as a list of values
  3112. flat_list = [cls._sympify(i) for i in dat]
  3113. rows = len(flat_list)
  3114. cols = 1 if rows else 0
  3115. elif evaluate and all(ismat(i) for i in dat):
  3116. # a column as a list of matrices
  3117. ncol = {i.cols for i in dat if any(i.shape)}
  3118. if ncol:
  3119. if len(ncol) != 1:
  3120. raise ValueError('mismatched dimensions')
  3121. flat_list = [_ for i in dat for r in i.tolist() for _ in r]
  3122. cols = ncol.pop()
  3123. rows = len(flat_list)//cols
  3124. else:
  3125. rows = cols = 0
  3126. flat_list = []
  3127. elif evaluate and any(ismat(i) for i in dat):
  3128. ncol = set()
  3129. flat_list = []
  3130. for i in dat:
  3131. if ismat(i):
  3132. flat_list.extend(
  3133. [k for j in i.tolist() for k in j])
  3134. if any(i.shape):
  3135. ncol.add(i.cols)
  3136. elif raw(i):
  3137. if i:
  3138. ncol.add(len(i))
  3139. flat_list.extend([cls._sympify(ij) for ij in i])
  3140. else:
  3141. ncol.add(1)
  3142. flat_list.append(i)
  3143. if len(ncol) > 1:
  3144. raise ValueError('mismatched dimensions')
  3145. cols = ncol.pop()
  3146. rows = len(flat_list)//cols
  3147. else:
  3148. # list of lists; each sublist is a logical row
  3149. # which might consist of many rows if the values in
  3150. # the row are matrices
  3151. flat_list = []
  3152. ncol = set()
  3153. rows = cols = 0
  3154. for row in dat:
  3155. if not is_sequence(row) and \
  3156. not getattr(row, 'is_Matrix', False):
  3157. raise ValueError('expecting list of lists')
  3158. if hasattr(row, '__array__'):
  3159. if 0 in row.shape:
  3160. continue
  3161. if evaluate and all(ismat(i) for i in row):
  3162. r, c, flatT = cls._handle_creation_inputs(
  3163. [i.T for i in row])
  3164. T = reshape(flatT, [c])
  3165. flat = \
  3166. [T[i][j] for j in range(c) for i in range(r)]
  3167. r, c = c, r
  3168. else:
  3169. r = 1
  3170. if getattr(row, 'is_Matrix', False):
  3171. c = 1
  3172. flat = [row]
  3173. else:
  3174. c = len(row)
  3175. flat = [cls._sympify(i) for i in row]
  3176. ncol.add(c)
  3177. if len(ncol) > 1:
  3178. raise ValueError('mismatched dimensions')
  3179. flat_list.extend(flat)
  3180. rows += r
  3181. cols = ncol.pop() if ncol else 0
  3182. elif len(args) == 3:
  3183. rows = as_int(args[0])
  3184. cols = as_int(args[1])
  3185. if rows < 0 or cols < 0:
  3186. raise ValueError("Cannot create a {} x {} matrix. "
  3187. "Both dimensions must be positive".format(rows, cols))
  3188. # Matrix(2, 2, lambda i, j: i+j)
  3189. if len(args) == 3 and isinstance(args[2], Callable):
  3190. op = args[2]
  3191. flat_list = []
  3192. for i in range(rows):
  3193. flat_list.extend(
  3194. [cls._sympify(op(cls._sympify(i), cls._sympify(j)))
  3195. for j in range(cols)])
  3196. # Matrix(2, 2, [1, 2, 3, 4])
  3197. elif len(args) == 3 and is_sequence(args[2]):
  3198. flat_list = args[2]
  3199. if len(flat_list) != rows * cols:
  3200. raise ValueError(
  3201. 'List length should be equal to rows*columns')
  3202. flat_list = [cls._sympify(i) for i in flat_list]
  3203. # Matrix()
  3204. elif len(args) == 0:
  3205. # Empty Matrix
  3206. rows = cols = 0
  3207. flat_list = []
  3208. if flat_list is None:
  3209. raise TypeError(filldedent('''
  3210. Data type not understood; expecting list of lists
  3211. or lists of values.'''))
  3212. return rows, cols, flat_list
  3213. def _setitem(self, key, value):
  3214. """Helper to set value at location given by key.
  3215. Examples
  3216. ========
  3217. >>> from sympy import Matrix, I, zeros, ones
  3218. >>> m = Matrix(((1, 2+I), (3, 4)))
  3219. >>> m
  3220. Matrix([
  3221. [1, 2 + I],
  3222. [3, 4]])
  3223. >>> m[1, 0] = 9
  3224. >>> m
  3225. Matrix([
  3226. [1, 2 + I],
  3227. [9, 4]])
  3228. >>> m[1, 0] = [[0, 1]]
  3229. To replace row r you assign to position r*m where m
  3230. is the number of columns:
  3231. >>> M = zeros(4)
  3232. >>> m = M.cols
  3233. >>> M[3*m] = ones(1, m)*2; M
  3234. Matrix([
  3235. [0, 0, 0, 0],
  3236. [0, 0, 0, 0],
  3237. [0, 0, 0, 0],
  3238. [2, 2, 2, 2]])
  3239. And to replace column c you can assign to position c:
  3240. >>> M[2] = ones(m, 1)*4; M
  3241. Matrix([
  3242. [0, 0, 4, 0],
  3243. [0, 0, 4, 0],
  3244. [0, 0, 4, 0],
  3245. [2, 2, 4, 2]])
  3246. """
  3247. from .dense import Matrix
  3248. is_slice = isinstance(key, slice)
  3249. i, j = key = self.key2ij(key)
  3250. is_mat = isinstance(value, MatrixBase)
  3251. if isinstance(i, slice) or isinstance(j, slice):
  3252. if is_mat:
  3253. self.copyin_matrix(key, value)
  3254. return
  3255. if not isinstance(value, Expr) and is_sequence(value):
  3256. self.copyin_list(key, value)
  3257. return
  3258. raise ValueError('unexpected value: %s' % value)
  3259. else:
  3260. if (not is_mat and
  3261. not isinstance(value, Basic) and is_sequence(value)):
  3262. value = Matrix(value)
  3263. is_mat = True
  3264. if is_mat:
  3265. if is_slice:
  3266. key = (slice(*divmod(i, self.cols)),
  3267. slice(*divmod(j, self.cols)))
  3268. else:
  3269. key = (slice(i, i + value.rows),
  3270. slice(j, j + value.cols))
  3271. self.copyin_matrix(key, value)
  3272. else:
  3273. return i, j, self._sympify(value)
  3274. return
  3275. def add(self, b):
  3276. """Return self + b."""
  3277. return self + b
  3278. def condition_number(self):
  3279. """Returns the condition number of a matrix.
  3280. This is the maximum singular value divided by the minimum singular value
  3281. Examples
  3282. ========
  3283. >>> from sympy import Matrix, S
  3284. >>> A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]])
  3285. >>> A.condition_number()
  3286. 100
  3287. See Also
  3288. ========
  3289. singular_values
  3290. """
  3291. if not self:
  3292. return self.zero
  3293. singularvalues = self.singular_values()
  3294. return Max(*singularvalues) / Min(*singularvalues)
  3295. def copy(self):
  3296. """
  3297. Returns the copy of a matrix.
  3298. Examples
  3299. ========
  3300. >>> from sympy import Matrix
  3301. >>> A = Matrix(2, 2, [1, 2, 3, 4])
  3302. >>> A.copy()
  3303. Matrix([
  3304. [1, 2],
  3305. [3, 4]])
  3306. """
  3307. return self._new(self.rows, self.cols, self.flat())
  3308. def cross(self, b):
  3309. r"""
  3310. Return the cross product of ``self`` and ``b`` relaxing the condition
  3311. of compatible dimensions: if each has 3 elements, a matrix of the
  3312. same type and shape as ``self`` will be returned. If ``b`` has the same
  3313. shape as ``self`` then common identities for the cross product (like
  3314. `a \times b = - b \times a`) will hold.
  3315. Parameters
  3316. ==========
  3317. b : 3x1 or 1x3 Matrix
  3318. See Also
  3319. ========
  3320. dot
  3321. hat
  3322. vee
  3323. multiply
  3324. multiply_elementwise
  3325. """
  3326. from sympy.matrices.expressions.matexpr import MatrixExpr
  3327. if not isinstance(b, (MatrixBase, MatrixExpr)):
  3328. raise TypeError(
  3329. "{} must be a Matrix, not {}.".format(b, type(b)))
  3330. if not (self.rows * self.cols == b.rows * b.cols == 3):
  3331. raise ShapeError("Dimensions incorrect for cross product: %s x %s" %
  3332. ((self.rows, self.cols), (b.rows, b.cols)))
  3333. else:
  3334. return self._new(self.rows, self.cols, (
  3335. (self[1] * b[2] - self[2] * b[1]),
  3336. (self[2] * b[0] - self[0] * b[2]),
  3337. (self[0] * b[1] - self[1] * b[0])))
  3338. def hat(self):
  3339. r"""
  3340. Return the skew-symmetric matrix representing the cross product,
  3341. so that ``self.hat() * b`` is equivalent to ``self.cross(b)``.
  3342. Examples
  3343. ========
  3344. Calling ``hat`` creates a skew-symmetric 3x3 Matrix from a 3x1 Matrix:
  3345. >>> from sympy import Matrix
  3346. >>> a = Matrix([1, 2, 3])
  3347. >>> a.hat()
  3348. Matrix([
  3349. [ 0, -3, 2],
  3350. [ 3, 0, -1],
  3351. [-2, 1, 0]])
  3352. Multiplying it with another 3x1 Matrix calculates the cross product:
  3353. >>> b = Matrix([3, 2, 1])
  3354. >>> a.hat() * b
  3355. Matrix([
  3356. [-4],
  3357. [ 8],
  3358. [-4]])
  3359. Which is equivalent to calling the ``cross`` method:
  3360. >>> a.cross(b)
  3361. Matrix([
  3362. [-4],
  3363. [ 8],
  3364. [-4]])
  3365. See Also
  3366. ========
  3367. dot
  3368. cross
  3369. vee
  3370. multiply
  3371. multiply_elementwise
  3372. """
  3373. if self.shape != (3, 1):
  3374. raise ShapeError("Dimensions incorrect, expected (3, 1), got " +
  3375. str(self.shape))
  3376. else:
  3377. x, y, z = self
  3378. return self._new(3, 3, (
  3379. 0, -z, y,
  3380. z, 0, -x,
  3381. -y, x, 0))
  3382. def vee(self):
  3383. r"""
  3384. Return a 3x1 vector from a skew-symmetric matrix representing the cross product,
  3385. so that ``self * b`` is equivalent to ``self.vee().cross(b)``.
  3386. Examples
  3387. ========
  3388. Calling ``vee`` creates a vector from a skew-symmetric Matrix:
  3389. >>> from sympy import Matrix
  3390. >>> A = Matrix([[0, -3, 2], [3, 0, -1], [-2, 1, 0]])
  3391. >>> a = A.vee()
  3392. >>> a
  3393. Matrix([
  3394. [1],
  3395. [2],
  3396. [3]])
  3397. Calculating the matrix product of the original matrix with a vector
  3398. is equivalent to a cross product:
  3399. >>> b = Matrix([3, 2, 1])
  3400. >>> A * b
  3401. Matrix([
  3402. [-4],
  3403. [ 8],
  3404. [-4]])
  3405. >>> a.cross(b)
  3406. Matrix([
  3407. [-4],
  3408. [ 8],
  3409. [-4]])
  3410. ``vee`` can also be used to retrieve angular velocity expressions.
  3411. Defining a rotation matrix:
  3412. >>> from sympy import rot_ccw_axis3, trigsimp
  3413. >>> from sympy.physics.mechanics import dynamicsymbols
  3414. >>> theta = dynamicsymbols('theta')
  3415. >>> R = rot_ccw_axis3(theta)
  3416. >>> R
  3417. Matrix([
  3418. [cos(theta(t)), -sin(theta(t)), 0],
  3419. [sin(theta(t)), cos(theta(t)), 0],
  3420. [ 0, 0, 1]])
  3421. We can retrieve the angular velocity:
  3422. >>> Omega = R.T * R.diff()
  3423. >>> Omega = trigsimp(Omega)
  3424. >>> Omega.vee()
  3425. Matrix([
  3426. [ 0],
  3427. [ 0],
  3428. [Derivative(theta(t), t)]])
  3429. See Also
  3430. ========
  3431. dot
  3432. cross
  3433. hat
  3434. multiply
  3435. multiply_elementwise
  3436. """
  3437. if self.shape != (3, 3):
  3438. raise ShapeError("Dimensions incorrect, expected (3, 3), got " +
  3439. str(self.shape))
  3440. elif not self.is_anti_symmetric():
  3441. raise ValueError("Matrix is not skew-symmetric")
  3442. else:
  3443. return self._new(3, 1, (
  3444. self[2, 1],
  3445. self[0, 2],
  3446. self[1, 0]))
  3447. @property
  3448. def D(self):
  3449. """Return Dirac conjugate (if ``self.rows == 4``).
  3450. Examples
  3451. ========
  3452. >>> from sympy import Matrix, I, eye
  3453. >>> m = Matrix((0, 1 + I, 2, 3))
  3454. >>> m.D
  3455. Matrix([[0, 1 - I, -2, -3]])
  3456. >>> m = (eye(4) + I*eye(4))
  3457. >>> m[0, 3] = 2
  3458. >>> m.D
  3459. Matrix([
  3460. [1 - I, 0, 0, 0],
  3461. [ 0, 1 - I, 0, 0],
  3462. [ 0, 0, -1 + I, 0],
  3463. [ 2, 0, 0, -1 + I]])
  3464. If the matrix does not have 4 rows an AttributeError will be raised
  3465. because this property is only defined for matrices with 4 rows.
  3466. >>> Matrix(eye(2)).D
  3467. Traceback (most recent call last):
  3468. ...
  3469. AttributeError: Matrix has no attribute D.
  3470. See Also
  3471. ========
  3472. sympy.matrices.matrixbase.MatrixBase.conjugate: By-element conjugation
  3473. sympy.matrices.matrixbase.MatrixBase.H: Hermite conjugation
  3474. """
  3475. from sympy.physics.matrices import mgamma
  3476. if self.rows != 4:
  3477. # In Python 3.2, properties can only return an AttributeError
  3478. # so we can't raise a ShapeError -- see commit which added the
  3479. # first line of this inline comment. Also, there is no need
  3480. # for a message since MatrixBase will raise the AttributeError
  3481. raise AttributeError
  3482. return self.H * mgamma(0)
  3483. def dot(self, b, hermitian=None, conjugate_convention=None):
  3484. """Return the dot or inner product of two vectors of equal length.
  3485. Here ``self`` must be a ``Matrix`` of size 1 x n or n x 1, and ``b``
  3486. must be either a matrix of size 1 x n, n x 1, or a list/tuple of length n.
  3487. A scalar is returned.
  3488. By default, ``dot`` does not conjugate ``self`` or ``b``, even if there are
  3489. complex entries. Set ``hermitian=True`` (and optionally a ``conjugate_convention``)
  3490. to compute the hermitian inner product.
  3491. Possible kwargs are ``hermitian`` and ``conjugate_convention``.
  3492. If ``conjugate_convention`` is ``"left"``, ``"math"`` or ``"maths"``,
  3493. the conjugate of the first vector (``self``) is used. If ``"right"``
  3494. or ``"physics"`` is specified, the conjugate of the second vector ``b`` is used.
  3495. Examples
  3496. ========
  3497. >>> from sympy import Matrix
  3498. >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
  3499. >>> v = Matrix([1, 1, 1])
  3500. >>> M.row(0).dot(v)
  3501. 6
  3502. >>> M.col(0).dot(v)
  3503. 12
  3504. >>> v = [3, 2, 1]
  3505. >>> M.row(0).dot(v)
  3506. 10
  3507. >>> from sympy import I
  3508. >>> q = Matrix([1*I, 1*I, 1*I])
  3509. >>> q.dot(q, hermitian=False)
  3510. -3
  3511. >>> q.dot(q, hermitian=True)
  3512. 3
  3513. >>> q1 = Matrix([1, 1, 1*I])
  3514. >>> q.dot(q1, hermitian=True, conjugate_convention="maths")
  3515. 1 - 2*I
  3516. >>> q.dot(q1, hermitian=True, conjugate_convention="physics")
  3517. 1 + 2*I
  3518. See Also
  3519. ========
  3520. cross
  3521. multiply
  3522. multiply_elementwise
  3523. """
  3524. from .dense import Matrix
  3525. if not isinstance(b, MatrixBase):
  3526. if is_sequence(b):
  3527. if len(b) != self.cols and len(b) != self.rows:
  3528. raise ShapeError(
  3529. "Dimensions incorrect for dot product: %s, %s" % (
  3530. self.shape, len(b)))
  3531. return self.dot(Matrix(b))
  3532. else:
  3533. raise TypeError(
  3534. "`b` must be an ordered iterable or Matrix, not %s." %
  3535. type(b))
  3536. if (1 not in self.shape) or (1 not in b.shape):
  3537. raise ShapeError
  3538. if len(self) != len(b):
  3539. raise ShapeError(
  3540. "Dimensions incorrect for dot product: %s, %s" % (self.shape, b.shape))
  3541. mat = self
  3542. n = len(mat)
  3543. if mat.shape != (1, n):
  3544. mat = mat.reshape(1, n)
  3545. if b.shape != (n, 1):
  3546. b = b.reshape(n, 1)
  3547. # Now ``mat`` is a row vector and ``b`` is a column vector.
  3548. # If it so happens that only conjugate_convention is passed
  3549. # then automatically set hermitian to True. If only hermitian
  3550. # is true but no conjugate_convention is not passed then
  3551. # automatically set it to ``"maths"``
  3552. if conjugate_convention is not None and hermitian is None:
  3553. hermitian = True
  3554. if hermitian and conjugate_convention is None:
  3555. conjugate_convention = "maths"
  3556. if hermitian == True:
  3557. if conjugate_convention in ("maths", "left", "math"):
  3558. mat = mat.conjugate()
  3559. elif conjugate_convention in ("physics", "right"):
  3560. b = b.conjugate()
  3561. else:
  3562. raise ValueError("Unknown conjugate_convention was entered."
  3563. " conjugate_convention must be one of the"
  3564. " following: math, maths, left, physics or right.")
  3565. return (mat * b)[0]
  3566. def dual(self):
  3567. """Returns the dual of a matrix.
  3568. A dual of a matrix is:
  3569. ``(1/2)*levicivita(i, j, k, l)*M(k, l)`` summed over indices `k` and `l`
  3570. Since the levicivita method is anti_symmetric for any pairwise
  3571. exchange of indices, the dual of a symmetric matrix is the zero
  3572. matrix. Strictly speaking the dual defined here assumes that the
  3573. 'matrix' `M` is a contravariant anti_symmetric second rank tensor,
  3574. so that the dual is a covariant second rank tensor.
  3575. """
  3576. from sympy.matrices import zeros
  3577. M, n = self[:, :], self.rows
  3578. work = zeros(n)
  3579. if self.is_symmetric():
  3580. return work
  3581. for i in range(1, n):
  3582. for j in range(1, n):
  3583. acum = 0
  3584. for k in range(1, n):
  3585. acum += LeviCivita(i, j, 0, k) * M[0, k]
  3586. work[i, j] = acum
  3587. work[j, i] = -acum
  3588. for l in range(1, n):
  3589. acum = 0
  3590. for a in range(1, n):
  3591. for b in range(1, n):
  3592. acum += LeviCivita(0, l, a, b) * M[a, b]
  3593. acum /= 2
  3594. work[0, l] = -acum
  3595. work[l, 0] = acum
  3596. return work
  3597. def _eval_matrix_exp_jblock(self):
  3598. """A helper function to compute an exponential of a Jordan block
  3599. matrix
  3600. Examples
  3601. ========
  3602. >>> from sympy import Symbol, Matrix
  3603. >>> l = Symbol('lamda')
  3604. A trivial example of 1*1 Jordan block:
  3605. >>> m = Matrix.jordan_block(1, l)
  3606. >>> m._eval_matrix_exp_jblock()
  3607. Matrix([[exp(lamda)]])
  3608. An example of 3*3 Jordan block:
  3609. >>> m = Matrix.jordan_block(3, l)
  3610. >>> m._eval_matrix_exp_jblock()
  3611. Matrix([
  3612. [exp(lamda), exp(lamda), exp(lamda)/2],
  3613. [ 0, exp(lamda), exp(lamda)],
  3614. [ 0, 0, exp(lamda)]])
  3615. References
  3616. ==========
  3617. .. [1] https://en.wikipedia.org/wiki/Matrix_function#Jordan_decomposition
  3618. """
  3619. size = self.rows
  3620. l = self[0, 0]
  3621. exp_l = exp(l)
  3622. bands = {i: exp_l / factorial(i) for i in range(size)}
  3623. from .sparsetools import banded
  3624. return self.__class__(banded(size, bands))
  3625. def analytic_func(self, f, x):
  3626. """
  3627. Computes f(A) where A is a Square Matrix
  3628. and f is an analytic function.
  3629. Examples
  3630. ========
  3631. >>> from sympy import Symbol, Matrix, S, log
  3632. >>> x = Symbol('x')
  3633. >>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]])
  3634. >>> f = log(x)
  3635. >>> m.analytic_func(f, x)
  3636. Matrix([
  3637. [ 0, log(2)],
  3638. [log(2), 0]])
  3639. Parameters
  3640. ==========
  3641. f : Expr
  3642. Analytic Function
  3643. x : Symbol
  3644. parameter of f
  3645. """
  3646. f, x = _sympify(f), _sympify(x)
  3647. if not self.is_square:
  3648. raise NonSquareMatrixError
  3649. if not x.is_symbol:
  3650. raise ValueError("{} must be a symbol.".format(x))
  3651. if x not in f.free_symbols:
  3652. raise ValueError(
  3653. "{} must be a parameter of {}.".format(x, f))
  3654. if x in self.free_symbols:
  3655. raise ValueError(
  3656. "{} must not be a parameter of {}.".format(x, self))
  3657. eigen = self.eigenvals()
  3658. max_mul = max(eigen.values())
  3659. derivative = {}
  3660. dd = f
  3661. for i in range(max_mul - 1):
  3662. dd = diff(dd, x)
  3663. derivative[i + 1] = dd
  3664. n = self.shape[0]
  3665. r = self.zeros(n)
  3666. f_val = self.zeros(n, 1)
  3667. row = 0
  3668. for i in eigen:
  3669. mul = eigen[i]
  3670. f_val[row] = f.subs(x, i)
  3671. if f_val[row].is_number and not f_val[row].is_complex:
  3672. raise ValueError(
  3673. "Cannot evaluate the function because the "
  3674. "function {} is not analytic at the given "
  3675. "eigenvalue {}".format(f, f_val[row]))
  3676. val = 1
  3677. for a in range(n):
  3678. r[row, a] = val
  3679. val *= i
  3680. if mul > 1:
  3681. coe = [1 for ii in range(n)]
  3682. deri = 1
  3683. while mul > 1:
  3684. row = row + 1
  3685. mul -= 1
  3686. d_i = derivative[deri].subs(x, i)
  3687. if d_i.is_number and not d_i.is_complex:
  3688. raise ValueError(
  3689. "Cannot evaluate the function because the "
  3690. "derivative {} is not analytic at the given "
  3691. "eigenvalue {}".format(derivative[deri], d_i))
  3692. f_val[row] = d_i
  3693. for a in range(n):
  3694. if a - deri + 1 <= 0:
  3695. r[row, a] = 0
  3696. coe[a] = 0
  3697. continue
  3698. coe[a] = coe[a]*(a - deri + 1)
  3699. r[row, a] = coe[a]*pow(i, a - deri)
  3700. deri += 1
  3701. row += 1
  3702. c = r.solve(f_val)
  3703. ans = self.zeros(n)
  3704. pre = self.eye(n)
  3705. for i in range(n):
  3706. ans = ans + c[i]*pre
  3707. pre *= self
  3708. return ans
  3709. def exp(self):
  3710. """Return the exponential of a square matrix.
  3711. Examples
  3712. ========
  3713. >>> from sympy import Symbol, Matrix
  3714. >>> t = Symbol('t')
  3715. >>> m = Matrix([[0, 1], [-1, 0]]) * t
  3716. >>> m.exp()
  3717. Matrix([
  3718. [ exp(I*t)/2 + exp(-I*t)/2, -I*exp(I*t)/2 + I*exp(-I*t)/2],
  3719. [I*exp(I*t)/2 - I*exp(-I*t)/2, exp(I*t)/2 + exp(-I*t)/2]])
  3720. """
  3721. if not self.is_square:
  3722. raise NonSquareMatrixError(
  3723. "Exponentiation is valid only for square matrices")
  3724. try:
  3725. P, J = self.jordan_form()
  3726. cells = J.get_diag_blocks()
  3727. except MatrixError:
  3728. raise NotImplementedError(
  3729. "Exponentiation is implemented only for matrices for which the Jordan normal form can be computed")
  3730. blocks = [cell._eval_matrix_exp_jblock() for cell in cells]
  3731. from sympy.matrices import diag
  3732. eJ = diag(*blocks)
  3733. # n = self.rows
  3734. ret = P.multiply(eJ, dotprodsimp=None).multiply(P.inv(), dotprodsimp=None)
  3735. if all(value.is_real for value in self.values()):
  3736. return type(self)(re(ret))
  3737. else:
  3738. return type(self)(ret)
  3739. def _eval_matrix_log_jblock(self):
  3740. """Helper function to compute logarithm of a jordan block.
  3741. Examples
  3742. ========
  3743. >>> from sympy import Symbol, Matrix
  3744. >>> l = Symbol('lamda')
  3745. A trivial example of 1*1 Jordan block:
  3746. >>> m = Matrix.jordan_block(1, l)
  3747. >>> m._eval_matrix_log_jblock()
  3748. Matrix([[log(lamda)]])
  3749. An example of 3*3 Jordan block:
  3750. >>> m = Matrix.jordan_block(3, l)
  3751. >>> m._eval_matrix_log_jblock()
  3752. Matrix([
  3753. [log(lamda), 1/lamda, -1/(2*lamda**2)],
  3754. [ 0, log(lamda), 1/lamda],
  3755. [ 0, 0, log(lamda)]])
  3756. """
  3757. size = self.rows
  3758. l = self[0, 0]
  3759. if l.is_zero:
  3760. raise MatrixError(
  3761. 'Could not take logarithm or reciprocal for the given '
  3762. 'eigenvalue {}'.format(l))
  3763. bands = {0: log(l)}
  3764. for i in range(1, size):
  3765. bands[i] = -((-l) ** -i) / i
  3766. from .sparsetools import banded
  3767. return self.__class__(banded(size, bands))
  3768. def log(self, simplify=cancel):
  3769. """Return the logarithm of a square matrix.
  3770. Parameters
  3771. ==========
  3772. simplify : function, bool
  3773. The function to simplify the result with.
  3774. Default is ``cancel``, which is effective to reduce the
  3775. expression growing for taking reciprocals and inverses for
  3776. symbolic matrices.
  3777. Examples
  3778. ========
  3779. >>> from sympy import S, Matrix
  3780. Examples for positive-definite matrices:
  3781. >>> m = Matrix([[1, 1], [0, 1]])
  3782. >>> m.log()
  3783. Matrix([
  3784. [0, 1],
  3785. [0, 0]])
  3786. >>> m = Matrix([[S(5)/4, S(3)/4], [S(3)/4, S(5)/4]])
  3787. >>> m.log()
  3788. Matrix([
  3789. [ 0, log(2)],
  3790. [log(2), 0]])
  3791. Examples for non positive-definite matrices:
  3792. >>> m = Matrix([[S(3)/4, S(5)/4], [S(5)/4, S(3)/4]])
  3793. >>> m.log()
  3794. Matrix([
  3795. [ I*pi/2, log(2) - I*pi/2],
  3796. [log(2) - I*pi/2, I*pi/2]])
  3797. >>> m = Matrix(
  3798. ... [[0, 0, 0, 1],
  3799. ... [0, 0, 1, 0],
  3800. ... [0, 1, 0, 0],
  3801. ... [1, 0, 0, 0]])
  3802. >>> m.log()
  3803. Matrix([
  3804. [ I*pi/2, 0, 0, -I*pi/2],
  3805. [ 0, I*pi/2, -I*pi/2, 0],
  3806. [ 0, -I*pi/2, I*pi/2, 0],
  3807. [-I*pi/2, 0, 0, I*pi/2]])
  3808. """
  3809. if not self.is_square:
  3810. raise NonSquareMatrixError(
  3811. "Logarithm is valid only for square matrices")
  3812. try:
  3813. if simplify:
  3814. P, J = simplify(self).jordan_form()
  3815. else:
  3816. P, J = self.jordan_form()
  3817. cells = J.get_diag_blocks()
  3818. except MatrixError:
  3819. raise NotImplementedError(
  3820. "Logarithm is implemented only for matrices for which "
  3821. "the Jordan normal form can be computed")
  3822. blocks = [
  3823. cell._eval_matrix_log_jblock()
  3824. for cell in cells]
  3825. from sympy.matrices import diag
  3826. eJ = diag(*blocks)
  3827. if simplify:
  3828. ret = simplify(P * eJ * simplify(P.inv()))
  3829. ret = self.__class__(ret)
  3830. else:
  3831. ret = P * eJ * P.inv()
  3832. return ret
  3833. def is_nilpotent(self):
  3834. """Checks if a matrix is nilpotent.
  3835. A matrix B is nilpotent if for some integer k, B**k is
  3836. a zero matrix.
  3837. Examples
  3838. ========
  3839. >>> from sympy import Matrix
  3840. >>> a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]])
  3841. >>> a.is_nilpotent()
  3842. True
  3843. >>> a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]])
  3844. >>> a.is_nilpotent()
  3845. False
  3846. """
  3847. if not self:
  3848. return True
  3849. if not self.is_square:
  3850. raise NonSquareMatrixError(
  3851. "Nilpotency is valid only for square matrices")
  3852. x = uniquely_named_symbol('x', self, modify=lambda s: '_' + s)
  3853. p = self.charpoly(x)
  3854. if p.args[0] == x ** self.rows:
  3855. return True
  3856. return False
  3857. def key2bounds(self, keys):
  3858. """Converts a key with potentially mixed types of keys (integer and slice)
  3859. into a tuple of ranges and raises an error if any index is out of ``self``'s
  3860. range.
  3861. See Also
  3862. ========
  3863. key2ij
  3864. """
  3865. islice, jslice = [isinstance(k, slice) for k in keys]
  3866. if islice:
  3867. if not self.rows:
  3868. rlo = rhi = 0
  3869. else:
  3870. rlo, rhi = keys[0].indices(self.rows)[:2]
  3871. else:
  3872. rlo = a2idx(keys[0], self.rows)
  3873. rhi = rlo + 1
  3874. if jslice:
  3875. if not self.cols:
  3876. clo = chi = 0
  3877. else:
  3878. clo, chi = keys[1].indices(self.cols)[:2]
  3879. else:
  3880. clo = a2idx(keys[1], self.cols)
  3881. chi = clo + 1
  3882. return rlo, rhi, clo, chi
  3883. def key2ij(self, key):
  3884. """Converts key into canonical form, converting integers or indexable
  3885. items into valid integers for ``self``'s range or returning slices
  3886. unchanged.
  3887. See Also
  3888. ========
  3889. key2bounds
  3890. """
  3891. if is_sequence(key):
  3892. if not len(key) == 2:
  3893. raise TypeError('key must be a sequence of length 2')
  3894. return [a2idx(i, n) if not isinstance(i, slice) else i
  3895. for i, n in zip(key, self.shape)]
  3896. elif isinstance(key, slice):
  3897. return key.indices(len(self))[:2]
  3898. else:
  3899. return divmod(a2idx(key, len(self)), self.cols)
  3900. def normalized(self, iszerofunc=_iszero):
  3901. """Return the normalized version of ``self``.
  3902. Parameters
  3903. ==========
  3904. iszerofunc : Function, optional
  3905. A function to determine whether ``self`` is a zero vector.
  3906. The default ``_iszero`` tests to see if each element is
  3907. exactly zero.
  3908. Returns
  3909. =======
  3910. Matrix
  3911. Normalized vector form of ``self``.
  3912. It has the same length as a unit vector. However, a zero vector
  3913. will be returned for a vector with norm 0.
  3914. Raises
  3915. ======
  3916. ShapeError
  3917. If the matrix is not in a vector form.
  3918. See Also
  3919. ========
  3920. norm
  3921. """
  3922. if self.rows != 1 and self.cols != 1:
  3923. raise ShapeError("A Matrix must be a vector to normalize.")
  3924. norm = self.norm()
  3925. if iszerofunc(norm):
  3926. out = self.zeros(self.rows, self.cols)
  3927. else:
  3928. out = self.applyfunc(lambda i: i / norm)
  3929. return out
  3930. def norm(self, ord=None):
  3931. """Return the Norm of a Matrix or Vector.
  3932. In the simplest case this is the geometric size of the vector
  3933. Other norms can be specified by the ord parameter
  3934. ===== ============================ ==========================
  3935. ord norm for matrices norm for vectors
  3936. ===== ============================ ==========================
  3937. None Frobenius norm 2-norm
  3938. 'fro' Frobenius norm - does not exist
  3939. inf maximum row sum max(abs(x))
  3940. -inf -- min(abs(x))
  3941. 1 maximum column sum as below
  3942. -1 -- as below
  3943. 2 2-norm (largest sing. value) as below
  3944. -2 smallest singular value as below
  3945. other - does not exist sum(abs(x)**ord)**(1./ord)
  3946. ===== ============================ ==========================
  3947. Examples
  3948. ========
  3949. >>> from sympy import Matrix, Symbol, trigsimp, cos, sin, oo
  3950. >>> x = Symbol('x', real=True)
  3951. >>> v = Matrix([cos(x), sin(x)])
  3952. >>> trigsimp( v.norm() )
  3953. 1
  3954. >>> v.norm(10)
  3955. (sin(x)**10 + cos(x)**10)**(1/10)
  3956. >>> A = Matrix([[1, 1], [1, 1]])
  3957. >>> A.norm(1) # maximum sum of absolute values of A is 2
  3958. 2
  3959. >>> A.norm(2) # Spectral norm (max of |Ax|/|x| under 2-vector-norm)
  3960. 2
  3961. >>> A.norm(-2) # Inverse spectral norm (smallest singular value)
  3962. 0
  3963. >>> A.norm() # Frobenius Norm
  3964. 2
  3965. >>> A.norm(oo) # Infinity Norm
  3966. 2
  3967. >>> Matrix([1, -2]).norm(oo)
  3968. 2
  3969. >>> Matrix([-1, 2]).norm(-oo)
  3970. 1
  3971. See Also
  3972. ========
  3973. normalized
  3974. """
  3975. # Row or Column Vector Norms
  3976. vals = list(self.values()) or [0]
  3977. if S.One in self.shape:
  3978. if ord in (2, None): # Common case sqrt(<x, x>)
  3979. return sqrt(Add(*(abs(i) ** 2 for i in vals)))
  3980. elif ord == 1: # sum(abs(x))
  3981. return Add(*(abs(i) for i in vals))
  3982. elif ord is S.Infinity: # max(abs(x))
  3983. return Max(*[abs(i) for i in vals])
  3984. elif ord is S.NegativeInfinity: # min(abs(x))
  3985. return Min(*[abs(i) for i in vals])
  3986. # Otherwise generalize the 2-norm, Sum(x_i**ord)**(1/ord)
  3987. # Note that while useful this is not mathematically a norm
  3988. try:
  3989. return Pow(Add(*(abs(i) ** ord for i in vals)), S.One / ord)
  3990. except (NotImplementedError, TypeError):
  3991. raise ValueError("Expected order to be Number, Symbol, oo")
  3992. # Matrix Norms
  3993. else:
  3994. if ord == 1: # Maximum column sum
  3995. m = self.applyfunc(abs)
  3996. return Max(*[sum(m.col(i)) for i in range(m.cols)])
  3997. elif ord == 2: # Spectral Norm
  3998. # Maximum singular value
  3999. return Max(*self.singular_values())
  4000. elif ord == -2:
  4001. # Minimum singular value
  4002. return Min(*self.singular_values())
  4003. elif ord is S.Infinity: # Infinity Norm - Maximum row sum
  4004. m = self.applyfunc(abs)
  4005. return Max(*[sum(m.row(i)) for i in range(m.rows)])
  4006. elif (ord is None or isinstance(ord,
  4007. str) and ord.lower() in
  4008. ['f', 'fro', 'frobenius', 'vector']):
  4009. # Reshape as vector and send back to norm function
  4010. return self.vec().norm(ord=2)
  4011. else:
  4012. raise NotImplementedError("Matrix Norms under development")
  4013. def print_nonzero(self, symb="X"):
  4014. """Shows location of non-zero entries for fast shape lookup.
  4015. Examples
  4016. ========
  4017. >>> from sympy import Matrix, eye
  4018. >>> m = Matrix(2, 3, lambda i, j: i*3+j)
  4019. >>> m
  4020. Matrix([
  4021. [0, 1, 2],
  4022. [3, 4, 5]])
  4023. >>> m.print_nonzero()
  4024. [ XX]
  4025. [XXX]
  4026. >>> m = eye(4)
  4027. >>> m.print_nonzero("x")
  4028. [x ]
  4029. [ x ]
  4030. [ x ]
  4031. [ x]
  4032. """
  4033. s = []
  4034. for i in range(self.rows):
  4035. line = []
  4036. for j in range(self.cols):
  4037. if self[i, j] == 0:
  4038. line.append(" ")
  4039. else:
  4040. line.append(str(symb))
  4041. s.append("[%s]" % ''.join(line))
  4042. print('\n'.join(s))
  4043. def project(self, v):
  4044. """Return the projection of ``self`` onto the line containing ``v``.
  4045. Examples
  4046. ========
  4047. >>> from sympy import Matrix, S, sqrt
  4048. >>> V = Matrix([sqrt(3)/2, S.Half])
  4049. >>> x = Matrix([[1, 0]])
  4050. >>> V.project(x)
  4051. Matrix([[sqrt(3)/2, 0]])
  4052. >>> V.project(-x)
  4053. Matrix([[sqrt(3)/2, 0]])
  4054. """
  4055. return v * (self.dot(v) / v.dot(v))
  4056. def table(self, printer, rowstart='[', rowend=']', rowsep='\n',
  4057. colsep=', ', align='right'):
  4058. r"""
  4059. String form of Matrix as a table.
  4060. ``printer`` is the printer to use for on the elements (generally
  4061. something like StrPrinter())
  4062. ``rowstart`` is the string used to start each row (by default '[').
  4063. ``rowend`` is the string used to end each row (by default ']').
  4064. ``rowsep`` is the string used to separate rows (by default a newline).
  4065. ``colsep`` is the string used to separate columns (by default ', ').
  4066. ``align`` defines how the elements are aligned. Must be one of 'left',
  4067. 'right', or 'center'. You can also use '<', '>', and '^' to mean the
  4068. same thing, respectively.
  4069. This is used by the string printer for Matrix.
  4070. Examples
  4071. ========
  4072. >>> from sympy import Matrix, StrPrinter
  4073. >>> M = Matrix([[1, 2], [-33, 4]])
  4074. >>> printer = StrPrinter()
  4075. >>> M.table(printer)
  4076. '[ 1, 2]\n[-33, 4]'
  4077. >>> print(M.table(printer))
  4078. [ 1, 2]
  4079. [-33, 4]
  4080. >>> print(M.table(printer, rowsep=',\n'))
  4081. [ 1, 2],
  4082. [-33, 4]
  4083. >>> print('[%s]' % M.table(printer, rowsep=',\n'))
  4084. [[ 1, 2],
  4085. [-33, 4]]
  4086. >>> print(M.table(printer, colsep=' '))
  4087. [ 1 2]
  4088. [-33 4]
  4089. >>> print(M.table(printer, align='center'))
  4090. [ 1 , 2]
  4091. [-33, 4]
  4092. >>> print(M.table(printer, rowstart='{', rowend='}'))
  4093. { 1, 2}
  4094. {-33, 4}
  4095. """
  4096. # Handle zero dimensions:
  4097. if S.Zero in self.shape:
  4098. return '[]'
  4099. # Build table of string representations of the elements
  4100. res = []
  4101. # Track per-column max lengths for pretty alignment
  4102. maxlen = [0] * self.cols
  4103. for i in range(self.rows):
  4104. res.append([])
  4105. for j in range(self.cols):
  4106. s = printer._print(self[i, j])
  4107. res[-1].append(s)
  4108. maxlen[j] = max(len(s), maxlen[j])
  4109. # Patch strings together
  4110. align = {
  4111. 'left': 'ljust',
  4112. 'right': 'rjust',
  4113. 'center': 'center',
  4114. '<': 'ljust',
  4115. '>': 'rjust',
  4116. '^': 'center',
  4117. }[align]
  4118. for i, row in enumerate(res):
  4119. for j, elem in enumerate(row):
  4120. row[j] = getattr(elem, align)(maxlen[j])
  4121. res[i] = rowstart + colsep.join(row) + rowend
  4122. return rowsep.join(res)
  4123. def rank_decomposition(self, iszerofunc=_iszero, simplify=False):
  4124. return _rank_decomposition(self, iszerofunc=iszerofunc,
  4125. simplify=simplify)
  4126. def cholesky(self, hermitian=True):
  4127. raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
  4128. def LDLdecomposition(self, hermitian=True):
  4129. raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
  4130. def LUdecomposition(self, iszerofunc=_iszero, simpfunc=None,
  4131. rankcheck=False):
  4132. return _LUdecomposition(self, iszerofunc=iszerofunc, simpfunc=simpfunc,
  4133. rankcheck=rankcheck)
  4134. def LUdecomposition_Simple(self, iszerofunc=_iszero, simpfunc=None,
  4135. rankcheck=False):
  4136. return _LUdecomposition_Simple(self, iszerofunc=iszerofunc,
  4137. simpfunc=simpfunc, rankcheck=rankcheck)
  4138. def LUdecompositionFF(self):
  4139. return _LUdecompositionFF(self)
  4140. def singular_value_decomposition(self):
  4141. return _singular_value_decomposition(self)
  4142. def QRdecomposition(self):
  4143. return _QRdecomposition(self)
  4144. def upper_hessenberg_decomposition(self):
  4145. return _upper_hessenberg_decomposition(self)
  4146. def diagonal_solve(self, rhs):
  4147. return _diagonal_solve(self, rhs)
  4148. def lower_triangular_solve(self, rhs):
  4149. raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
  4150. def upper_triangular_solve(self, rhs):
  4151. raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix')
  4152. def cholesky_solve(self, rhs):
  4153. return _cholesky_solve(self, rhs)
  4154. def LDLsolve(self, rhs):
  4155. return _LDLsolve(self, rhs)
  4156. def LUsolve(self, rhs, iszerofunc=_iszero):
  4157. return _LUsolve(self, rhs, iszerofunc=iszerofunc)
  4158. def QRsolve(self, b):
  4159. return _QRsolve(self, b)
  4160. def gauss_jordan_solve(self, B, freevar=False):
  4161. return _gauss_jordan_solve(self, B, freevar=freevar)
  4162. def pinv_solve(self, B, arbitrary_matrix=None):
  4163. return _pinv_solve(self, B, arbitrary_matrix=arbitrary_matrix)
  4164. def cramer_solve(self, rhs, det_method="laplace"):
  4165. return _cramer_solve(self, rhs, det_method=det_method)
  4166. def solve(self, rhs, method='GJ'):
  4167. return _solve(self, rhs, method=method)
  4168. def solve_least_squares(self, rhs, method='CH'):
  4169. return _solve_least_squares(self, rhs, method=method)
  4170. def pinv(self, method='RD'):
  4171. return _pinv(self, method=method)
  4172. def inverse_ADJ(self, iszerofunc=_iszero):
  4173. return _inv_ADJ(self, iszerofunc=iszerofunc)
  4174. def inverse_BLOCK(self, iszerofunc=_iszero):
  4175. return _inv_block(self, iszerofunc=iszerofunc)
  4176. def inverse_GE(self, iszerofunc=_iszero):
  4177. return _inv_GE(self, iszerofunc=iszerofunc)
  4178. def inverse_LU(self, iszerofunc=_iszero):
  4179. return _inv_LU(self, iszerofunc=iszerofunc)
  4180. def inverse_CH(self, iszerofunc=_iszero):
  4181. return _inv_CH(self, iszerofunc=iszerofunc)
  4182. def inverse_LDL(self, iszerofunc=_iszero):
  4183. return _inv_LDL(self, iszerofunc=iszerofunc)
  4184. def inverse_QR(self, iszerofunc=_iszero):
  4185. return _inv_QR(self, iszerofunc=iszerofunc)
  4186. def inv(self, method=None, iszerofunc=_iszero, try_block_diag=False):
  4187. return _inv(self, method=method, iszerofunc=iszerofunc,
  4188. try_block_diag=try_block_diag)
  4189. def connected_components(self):
  4190. return _connected_components(self)
  4191. def connected_components_decomposition(self):
  4192. return _connected_components_decomposition(self)
  4193. def strongly_connected_components(self):
  4194. return _strongly_connected_components(self)
  4195. def strongly_connected_components_decomposition(self, lower=True):
  4196. return _strongly_connected_components_decomposition(self, lower=lower)
  4197. _sage_ = Basic._sage_
  4198. rank_decomposition.__doc__ = _rank_decomposition.__doc__
  4199. cholesky.__doc__ = _cholesky.__doc__
  4200. LDLdecomposition.__doc__ = _LDLdecomposition.__doc__
  4201. LUdecomposition.__doc__ = _LUdecomposition.__doc__
  4202. LUdecomposition_Simple.__doc__ = _LUdecomposition_Simple.__doc__
  4203. LUdecompositionFF.__doc__ = _LUdecompositionFF.__doc__
  4204. singular_value_decomposition.__doc__ = _singular_value_decomposition.__doc__
  4205. QRdecomposition.__doc__ = _QRdecomposition.__doc__
  4206. upper_hessenberg_decomposition.__doc__ = _upper_hessenberg_decomposition.__doc__
  4207. diagonal_solve.__doc__ = _diagonal_solve.__doc__
  4208. lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__
  4209. upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__
  4210. cholesky_solve.__doc__ = _cholesky_solve.__doc__
  4211. LDLsolve.__doc__ = _LDLsolve.__doc__
  4212. LUsolve.__doc__ = _LUsolve.__doc__
  4213. QRsolve.__doc__ = _QRsolve.__doc__
  4214. gauss_jordan_solve.__doc__ = _gauss_jordan_solve.__doc__
  4215. pinv_solve.__doc__ = _pinv_solve.__doc__
  4216. cramer_solve.__doc__ = _cramer_solve.__doc__
  4217. solve.__doc__ = _solve.__doc__
  4218. solve_least_squares.__doc__ = _solve_least_squares.__doc__
  4219. pinv.__doc__ = _pinv.__doc__
  4220. inverse_ADJ.__doc__ = _inv_ADJ.__doc__
  4221. inverse_GE.__doc__ = _inv_GE.__doc__
  4222. inverse_LU.__doc__ = _inv_LU.__doc__
  4223. inverse_CH.__doc__ = _inv_CH.__doc__
  4224. inverse_LDL.__doc__ = _inv_LDL.__doc__
  4225. inverse_QR.__doc__ = _inv_QR.__doc__
  4226. inverse_BLOCK.__doc__ = _inv_block.__doc__
  4227. inv.__doc__ = _inv.__doc__
  4228. connected_components.__doc__ = _connected_components.__doc__
  4229. connected_components_decomposition.__doc__ = \
  4230. _connected_components_decomposition.__doc__
  4231. strongly_connected_components.__doc__ = \
  4232. _strongly_connected_components.__doc__
  4233. strongly_connected_components_decomposition.__doc__ = \
  4234. _strongly_connected_components_decomposition.__doc__
  4235. def _convert_matrix(typ, mat):
  4236. """Convert mat to a Matrix of type typ."""
  4237. from sympy.matrices.matrixbase import MatrixBase
  4238. if getattr(mat, "is_Matrix", False) and not isinstance(mat, MatrixBase):
  4239. # This is needed for interop between Matrix and the redundant matrix
  4240. # mixin types like _MinimalMatrix etc. If anyone should happen to be
  4241. # using those then this keeps them working. Really _MinimalMatrix etc
  4242. # should be deprecated and removed though.
  4243. return typ(*mat.shape, list(mat))
  4244. else:
  4245. return typ(mat)
  4246. def _has_matrix_shape(other):
  4247. shape = getattr(other, 'shape', None)
  4248. if shape is None:
  4249. return False
  4250. return isinstance(shape, tuple) and len(shape) == 2
  4251. def _has_rows_cols(other):
  4252. return hasattr(other, 'rows') and hasattr(other, 'cols')
  4253. def _coerce_operand(self, other):
  4254. """Convert other to a Matrix, or check for possible scalar."""
  4255. INVALID = None, 'invalid_type'
  4256. # Disallow mixing Matrix and Array
  4257. if isinstance(other, NDimArray):
  4258. return INVALID
  4259. is_Matrix = getattr(other, 'is_Matrix', None)
  4260. # Return a Matrix as-is
  4261. if is_Matrix:
  4262. return other, 'is_matrix'
  4263. # Try to convert numpy array, mpmath matrix etc.
  4264. if is_Matrix is None:
  4265. if _has_matrix_shape(other) or _has_rows_cols(other):
  4266. return _convert_matrix(type(self), other), 'is_matrix'
  4267. # Could be a scalar but only if not iterable...
  4268. if not isinstance(other, Iterable):
  4269. return other, 'possible_scalar'
  4270. return INVALID
  4271. def classof(A, B):
  4272. """
  4273. Get the type of the result when combining matrices of different types.
  4274. Currently the strategy is that immutability is contagious.
  4275. Examples
  4276. ========
  4277. >>> from sympy import Matrix, ImmutableMatrix
  4278. >>> from sympy.matrices.matrixbase import classof
  4279. >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix
  4280. >>> IM = ImmutableMatrix([[1, 2], [3, 4]])
  4281. >>> classof(M, IM)
  4282. <class 'sympy.matrices.immutable.ImmutableDenseMatrix'>
  4283. """
  4284. priority_A = getattr(A, '_class_priority', None)
  4285. priority_B = getattr(B, '_class_priority', None)
  4286. if None not in (priority_A, priority_B):
  4287. if A._class_priority > B._class_priority:
  4288. return A.__class__
  4289. else:
  4290. return B.__class__
  4291. try:
  4292. import numpy
  4293. except ImportError:
  4294. pass
  4295. else:
  4296. if isinstance(A, numpy.ndarray):
  4297. return B.__class__
  4298. if isinstance(B, numpy.ndarray):
  4299. return A.__class__
  4300. raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__))
  4301. def _unify_with_other(self, other):
  4302. """Unify self and other into a single matrix type, or check for scalar."""
  4303. other, T = _coerce_operand(self, other)
  4304. if T == "is_matrix":
  4305. typ = classof(self, other)
  4306. if typ != self.__class__:
  4307. self = _convert_matrix(typ, self)
  4308. if typ != other.__class__:
  4309. other = _convert_matrix(typ, other)
  4310. return self, other, T
  4311. def a2idx(j, n=None):
  4312. """Return integer after making positive and validating against n."""
  4313. if not isinstance(j, int):
  4314. jindex = getattr(j, '__index__', None)
  4315. if jindex is not None:
  4316. j = jindex()
  4317. else:
  4318. raise IndexError("Invalid index a[%r]" % (j,))
  4319. if n is not None:
  4320. if j < 0:
  4321. j += n
  4322. if not (j >= 0 and j < n):
  4323. raise IndexError("Index out of range: a[%s]" % (j,))
  4324. return int(j)
  4325. class DeferredVector(Symbol, NotIterable): # type: ignore
  4326. """A vector whose components are deferred (e.g. for use with lambdify).
  4327. Examples
  4328. ========
  4329. >>> from sympy import DeferredVector, lambdify
  4330. >>> X = DeferredVector( 'X' )
  4331. >>> X
  4332. X
  4333. >>> expr = (X[0] + 2, X[2] + 3)
  4334. >>> func = lambdify( X, expr)
  4335. >>> func( [1, 2, 3] )
  4336. (3, 6)
  4337. """
  4338. def __getitem__(self, i):
  4339. if i == -0:
  4340. i = 0
  4341. if i < 0:
  4342. raise IndexError('DeferredVector index out of range')
  4343. component_name = '%s[%d]' % (self.name, i)
  4344. return Symbol(component_name)
  4345. def __str__(self):
  4346. return sstr(self)
  4347. def __repr__(self):
  4348. return "DeferredVector('%s')" % self.name