# Writing a matrix as a linear combination of matrices

Suppose I have two matrices A and B. After some calculations, I arrive at a matrix M and realize that M can be written as a linear combination of A and B,

M = a  A + b  B


for scalar constants a and b.

Is there a way to instruct Mathematica to express M as a A + b B?

In general, I am thinking of a function that takes a matrix M as an argument and explicitly writes it as a linear combination of a set of given matrices (in this case A and B).

Example:

A={{x,1},{0,y}};
B={{y^2,0},{x,2}}


From another calculation I have

M={{x+2y^2,1},{2x,y+4}};


I am looking for a function (or whatever can work) in Mathematica such that invoking f[M] produces:

A + 2*B


\$Version

(* "14.0.0 for Mac OS X ARM (64-bit) (December 13, 2023)" *)

Clear["Global*"]

A = {{x, 1}, {0, y}};
B = {{y^2, 0}, {x, 2}};

M = {{x + 2 y^2, 1}, {2 x, y + 4}};

sol = Solve[
{a, b}, {x, y}][[1]]

(* {a -> 1, b -> 2} *)


EDIT: Solve can automatically Thread

sol = Solve[a*A + b*B == M, {a, b}, {x, y}][[1]]

(* {a -> 1, b -> 2} *)


Verifying,

a*A + b*B == M /. sol

(* True *)

HoldForm[a*A + b*B] /. sol


• I need your help @Bob Hanlon for a numerical solution with Findroot Mar 3 at 23:05
• @Gallagher - post a question Mar 3 at 23:27
• Please @Bob Hanlon you can see my post mathematica.stackexchange.com/q/300202/58233 Mar 8 at 20:33
• Please @Bob Hanlon: can you intervene in my post mathematica.stackexchange.com/q/300202/58233 to plot Re[sol2] and Im[sol2] for 0<k<20`. Thank you. Mar 9 at 19:22
• Can you intervene @Bob Hanlon in my post mathematica.stackexchange.com/q/300202/58233? Mar 16 at 12:32