Group Abstract Group Abstract

Message Boards Message Boards

0
|
3.4K Views
|
3 Replies
|
2 Total Likes
View groups...
Share
Share this post:

Unexpected selection results using patterns

Posted 3 years ago

Hi

When extracting coefficients using patterns, I am having problems when the coefficient is 1 - see attached notebook. It appears that the coefficient of 1 is being ignored completed and instead the unknown is being selected.

Am I doing something incorrectly or should I report this as a possible programming problem?

Thanks,

Mitch Sandlin

POSTED BY: Mitchell Sandlin
3 Replies

One thing is that you are tacitly assuming the first factor will be the integer, and also using (perhaps intentionally) the fact that since m precedes n alphabetically, canonical ordering places it first in the pattern. It would be more reliable to use a pattern that forces m to be an integer and allows for the possibility that it "collapses" to one. Also I think you want to restrict the pattern to operate on level 1 of the expression. While there may be nicer/shorter/slicker ways to achieve this, I think Cases as shown below is a good function for this purpose. Since it returns a list we need to post-process to get a sum at the end.

In[82]:= Apply[Plus, 
 Cases[1*a + 2*b + 3*c + 4*d + 5*e, Optional[m_Integer, 1]*n_ :> m, {1}]]

(* Out[82]= 15 *)
POSTED BY: Daniel Lichtblau

A variation:

HoldForm[1*a + 2*b + 3*c + 4*d + 5*e] /. (m_?NumericQ)*n_Symbol :> m

or using Coefficient:

Map[Coefficient[1*a + 2*b + 3*c + 4*d + 5*e, #] &,
 {a, b, c, d, e}]
POSTED BY: Gianluca Gorni
Posted 3 years ago

Before the replace is applied, the expression is evaluated and put into standard form. Standard form eliminates the superfluous 1.

1*a + 2*b + 3*c + 4*d + 5*e // FullForm
(* Plus[a, Times[2, b], Times[3, c], Times[4, d], Times[5, e]] *)

You could try suppressing evaluation like this:

Unevaluated[1*a + 2*b + 3*c + 4*d + 5*e] //. m_*n_ :> m

But I don't know if that fits into your workflow.

POSTED BY: Eric Rimbey
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard