Re: Solve or LinearSolve or ...?

*To*: mathgroup at smc.vnet.net*Subject*: [mg46382] Re: [mg46347] Solve or LinearSolve or ...?*From*: Daniel Lichtblau <danl at wolfram.com>*Date*: Mon, 16 Feb 2004 23:42:15 -0500 (EST)*Sender*: owner-wri-mathgroup at wolfram.com

Scott Morrison wrote: > Hi, > > I'm trying to write a function to calculate coefficients in a basis; > for example > > FindCoefficients[{f[a,a],f[a,b],f[b,a],f[b,b]}, f[a,a]+(1/2)f[b,a], > _f] > > should produce {1,0,1/2,0}. The third argument there means `assuming > all objects matching _f are linearly independent'. More difficult, it > should produce > > FindCoefficients[{f[a]+f[b],f[a]-f[b]},f[a], _f] == {1/2,1/2}. > > And finally, it should work with rational functions as coefficients, > not just numbers, and it should run fast enough to be useful with > bases with thousands of elements. :-) > > I've spent quite some time trying to write something like this, and > I'm finding it really difficult! I can't seem to use LinearSolve in > any way -- it seems to trip up when I use rational functions as > coefficients. I've been trying to work around Solve, but the only > things that work are glacial in pace! > > Any ideas or suggestions? I'd be happy to post some of my attempts if > they'd be helpful in explaining what I'm trying to do, but mostly I'm > too embarrassed by them :-) > > Scott Morrison Here is one method that should be reasonably efficient. findCoefficients[ll_List, expr_, varhead_] := Module[ {cc, coeffs, newexpr, vars, eqns}, coeffs = Array[cc,Length[ll]]; newexpr = coeffs.ll - expr; vars = Cases[Variables[{ll,expr}], varhead]; eqns = Thread[Map[D[newexpr,#]&, vars] == 0]; coeffs /. First[Solve[eqns,coeffs]] ] In[34]:= InputForm[findCoefficients[{f[a,a],f[a,b],f[b,a],f[b,b]}, f[a,a]+(1/2)f[b,a], _f]] Out[34]//InputForm= {1, 0, 1/2, 0} In[35]:= InputForm[findCoefficients[{f[a]+f[b],f[a]-f[b]},f[a], _f]] Out[35]//InputForm= {1/2, 1/2} If this is slow on examples of interest then you may want to post further information describing such examples. Daniel Lichtblau Wolfram Research