开发者

Mathematica - selectively gathering nodes in a tree

I have a tree (expression) on which I want to gather only certain types of nodes - those that follow a certain pattern. I have a simplified example below:

A = {{{{},{0.3,0.3}},{0.2,0.2}},{0.1,0.1}};
TreeForm[A, PlotRangePadding->0]
Cases[A, {x_Real, y_Real}, Infinity]

The output:

Mathematica - selectively gathering nodes in a tree

Is this a good way to do it?

If instead of {x_, y_}, if I wanted to look for {{x1_, y1_}, {x2_, y_2}}, how can I exclude expressions like {x_, y_}, which also match?

Regards

EDIT (14/07/2011)

I have found that using a head other than List will greatly aid in finding such sub-expressions without collisions.

For example, reformulating the above:

A = {{{{}, pt[0.3, 0.3]}, pt[0.2, 0.2]}, pt[0.1, 0.1]};
List @@@ Cases[A, _pt, Infinity]

Output:

{{0.3,0.3},开发者_StackOverflow{0.2,0.2},{0.1,0.1}}


About the second part of your question, ie, selecting {{a,b},{c,d}}, how about

b = {{{{}, {0.3, 0.3}}, {0.2, 0.2}}, {{0.1, 0.1}, {0.3, 0.4}}};
TreeForm[b]
Cases[b, {{a_, b_}, {c_, d_}} /; (And @@ NumericQ /@ {a, b, c, d}), Infinity]

(so that they do not have to be Real but any Numeric will do)?


Here is an alternative to the form acl used, that I find more readable.

b = {{{{}, {0.3, 0.3}}, {0.2, 0.2}}, {{0.1, 0.1}, {0.3, 0.4}}};

With[{p = _?NumericQ}, Cases[b, {{p, p}, {p, p}}, -1] ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜