2
$\begingroup$

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

$\endgroup$
3
$\begingroup$
 n = 10000; konstants = ToExpression /@ ("c" <> # & /@ (ToString /@ Range[n]))
$\endgroup$
9
$\begingroup$

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]]
$\endgroup$
  • $\begingroup$ This is even better. This solves the actual problem. We can further do operations using these constants right? $\endgroup$ – acoustics Oct 25 '18 at 12:01
  • 1
    $\begingroup$ 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. $\endgroup$ – Niki Estner Oct 25 '18 at 12:05
  • 1
    $\begingroup$ Actually, there are a few differences, see mathematica.stackexchange.com/a/94298/242 - but in practice, in my experience, using c[...] as constants in a calculation makes life much simpler $\endgroup$ – Niki Estner Oct 25 '18 at 12:08
5
$\begingroup$
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).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.