2

Manually defining the constants is tedious if the 'n' is large. how to do this?

gwr
  • 13,452
  • 2
  • 47
  • 78
acoustics
  • 1,709
  • 9
  • 20

3 Answers3

10

Have you considered using c[1]..c[n] instead of c1..cn? Then you can just use constants = Array[c,n] to generate them, and they're much easier to handle later in the calculation.

For example, you could define a polynomial like this:

p = c[0] + Sum[c[i]*x^i, {i,4}];

Then later evaluate it for some specific set of constants:

actualCoefficients = Range[5]
p /. { c[i_] :> actualCoefficients[[i+1]] }

You can also calculate derivatives:

D[p, c[1]]

or perform optimization over these values:

FindMinimum[costTerm, Array[c,5]]
Niki Estner
  • 36,101
  • 3
  • 92
  • 152
  • This is even better. This solves the actual problem. We can further do operations using these constants right? – acoustics Oct 25 '18 at 12:01
  • 1
    Yes, you can usually use c[1] as a constant anywhere, just like c1 - just make sure you don't define the symbol c anywhere. – Niki Estner Oct 25 '18 at 12:05
  • 1
    Actually, there are a few differences, see https://mathematica.stackexchange.com/a/94298/242 - but in practice, in my experience, using c[...] as constants in a calculation makes life much simpler – Niki Estner Oct 25 '18 at 12:08
5
With[ {n = 10},  
    Array[ 
        Symbol[ "c" <> ToString @ #]&
        , n
    ] 
]

{c1, c2, c3, c4, c5, c6, c7, c8, c9, c10}

Update

Yes, usually using c[1], c[2], ... instead of c1, c2, ... is the better choice. Neverytheless, it must not be as cumbersome as it looks if we take up the examples provided by @Niki Estner:

indexedC = Array[ Symbol[ "c" <> ToString @ # ]&, 5 ];
(* {c0, c1, c2, c3, c4} *)

Then the polynomial given above can be constructed as follows:

p = Sum[ indexedC[[i]] x^( i - 1), {i, 5}];

And I do find the evaluation for actualCoefficients even clearer as Niki's pattern solution:

actualCoefficients = Range[5];
p /. Thread[ indexedC -> actualCoefficients ]

$1 + 2 x + 3 x^2 + 4 x^3 + 5 x^4$

So it is not as bad as it looks and avoids the problems with C[1] being a DownValue instead of an OwnValue (see this question).

gwr
  • 13,452
  • 2
  • 47
  • 78
3
 n = 10000; konstants = ToExpression /@ ("c" <> # & /@ (ToString /@ Range[n]))
Slepecky Mamut
  • 1,762
  • 7
  • 15