2
$\begingroup$

Suppose I have several lists:

lst1={{{x1,y1},{dx1,dy1}},{{x2,y2},{dx2,dy2}},...};
lst2={{{x1,y1},dy1},{{x2,y2},dy2},...};
lst3={{{x1,y1},{dx1,{dy1n,dy1p}}},{{x2,y2},{dx2,{dy2n,dy2p}}},...};

where there can be several hundred entries in each list. {xi,yi} are measured data which can have errors {dxi,dyi}. Additionally these do not need to be symmetric, e.g. {dxi,{dyin,dyip}}is also possible .

I want to write a function f[l_List] which checks the form of the given list and then proceed in different ways. Since the shape for a given list does not change, it is enough to check the first element.

For example:

g[l_List]:= If[ f[l[[1]]]=={{_,_},{_,_}} ,a ,b ]

Where a and b are further operations on that list. The problem I have is finding the correct formulation for the condition in the If-statement.

I came up with Dimensions[l[[1]]]=={1,2,2} which works for distinguishing lst1 and lst2, but fails for lst3, since Dimensions[lst1[[1]]]==Dimensions[lst3[[1]]]=={1,2,2}.

So the question is how this condition could look like.

Thanks in advance.

Additional question: How do I color my code like it is done in most questions on this side?

$\endgroup$
  • $\begingroup$ Indent your code by four spaces to get the code with syntax coloring (as opposed to inline code delimited by backticks). As for your actual problem, probably something like MatchQ[expr, {{_, _}, _}] might be useful. $\endgroup$ – J. M. will be back soon Aug 19 '17 at 16:12
  • $\begingroup$ I am not exactly sure how I was able to overlook this, but it does the job. One just needs to check the most nested structure first for it to work. Thanks! $\endgroup$ – ctrl Aug 19 '17 at 16:34
4
$\begingroup$

You can simply use the pattern describing your structure on the left side of SetDelayed:

f[l : {{{_, _}, {_, _}} ..}] := "Structure 1"
f[l : {{{_, _}, _} ..}] := "Structure 2"
f[l : {{{_, _}, {_, {_, _}}} ..}] := "Structure 3"

You can read up on patterns in the documentation. Note that Mathematica always uses the most specific pattern that matches: Even though the first definition would also match lst3, it's not taken since the third one is more specific.

Now, the correct one of these 3 definitions is used, depending on the structure of the list:

In[1]:=  f[lst1]
Out[1]:= "Structure 1"
In[2]:=  f[lst2]
Out[2]:= "Structure 2"
In[3]:=  f[lst3]
Out[3]:= "Structure 3"
$\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.