Mathematica Add Coefficient Lists in Mathematica: Learn How to Sum Groups of Coefficients

  • Thread starter Thread starter 76Ahmad
  • Start date Start date
  • Tags Tags
    Mathematica
AI Thread Summary
The discussion revolves around how to sum groups of coefficients generated from polynomial expressions in a programming context. The initial query presents a code snippet that uses nested loops to generate coefficient lists from polynomials modulated by prime numbers. The user seeks assistance in aggregating these coefficients into a single list for each polynomial degree.The solution provided emphasizes avoiding the use of Print for data extraction, suggesting instead to store results in a structured format. A modified approach is recommended, utilizing a more efficient method with the Table function and Select to filter prime numbers, which simplifies the process of summing the coefficients. The final output demonstrates the correct aggregated results for each polynomial degree, highlighting a more streamlined coding practice.
76Ahmad
Messages
46
Reaction score
0
Hi all, a quistion about how to add the cofficients list to gether?
here is an example:

For[m = 2, m ≤ 4 , m++,
For[p = 2, p ≤ m^2, p++,
If[PrimeQ[p], Print[CoefficientList[PolynomialMod[Expand[(1 - x)^m], p], x]]]]]

{1,0,1}
{1,1,1}

{1,1,1,1}
{1,0,0,2}
{1,2,3,4}
{1,4,3,6}

{1,0,0,0,1}
{1,2,0,2,1}
{1,1,1,1,1}
{1,3,6,3,1}
{1,7,6,7,1}
{1,9,6,9,1}


How to add every grup of cofficients together?
the reuslt should be like that:

{2,1,2}

{4,7,7,13}

{6,22,19,22,6}

please help :))
 
Physics news on Phys.org
In[4]:=For[m=2,m≤4,m++,
Print[
Apply[Plus,
Reap[
For[p=2,p≤m^2,p++,
If[PrimeQ[p],Sow[CoefficientList[PolynomialMod[Expand[(1-x)^m],p],x]]]
]
][[2,1]]
]
]
]

From In[4]:={2,1,2}
From In[4]:={4,7,7,13}
From In[4]:={6,22,19,22,6}
 
You don't really want to use Print[] to extract you data since it's not easily accessed after that.

The way to do what you want with a minimal modification of your code would to be something like

Code:
For[m = 2, m <= 4, m++,
 For[p = 2, p <= m^2, p++,
  If[PrimeQ[p], Print[data[m, p] = 
     CoefficientList[PolynomialMod[Expand[(1 - x)^m], p], x]], 
   data[m, p] = 0]]]
Table[Sum[data[m, p], {p, 2, m^2}], {m, 2, 4}]

which returns
Code:
{{2, 1, 2}, {4, 7, 7, 13}, {6, 22, 19, 22, 6}}

But you really should avoid using explicit Do's, For's, etc... as much as possible.

Something like

Code:
Table[Sum[
    CoefficientList[PolynomialMod[Expand[(1 - x)^m], p], x],
    {p, Select[Range[2, m^2], PrimeQ]}], 
  {m, 2, 4}]

might be a better way of getting the result...
 
Back
Top