1
$\begingroup$

I want to compare two arrays, using pattern matching. For example, suppose:

a1 = {{0, 0, 1}, {0, 0, 1}, {0, 0, 1}};

I would like to compare it to the pattern array:

p =  {{0, 0, x}, {0, 0, 1}, {0, 0, 1}};

that is, here x is arbitrary - it can take any value. So I would like to do something like:

a1==p 

and have it return true. If however,

a1 = {{0, 1, 1}, {0, 0, 1}, {0, 0, 1}};

then

a1==p

would return false.

I have about 12 different pattern matching arrays that I need to define, and then compare a given array to each pattern to the find which pattern that array follows. Some entries of the pattern are fixed, other are arbitrary. Another pattern array would look like:

p2 = {{0, 0, x}, {0, 0, 1}, {x, 1, 1}};

that is, as long as the 1's and 0's are in the same position, then the arrays are the same.

I'm not the most familiar with pattern matching coding in mathematica, I apologise if the solution is actually trivial as it is given in the function references within mathematica. Thanks in advance.

$\endgroup$
2
$\begingroup$

Pattern matching is a fundamental part of Mathematica. Read through these tutorials:

a1 = {{0, 0, 1}, {0, 0, 1}, {0, 0, 1}};
a2 = {{0, 1, 1}, {0, 0, 1}, {0, 0, 1}};

p  = {{0, 0, _}, {0, 0, 1}, {0, 0, 1}};

MatchQ[a1, p]
(* True *)

MatchQ[a2, p]
(* False *)
$\endgroup$
  • $\begingroup$ I see, I was using the _ notation in the pattern list, however I didn't realise that one had to use the MatchQ function. I appreciate the references. $\endgroup$ – Luca Pontiggia Oct 16 '17 at 17:23
1
$\begingroup$

One way to do without pattern matching is identifying where the variable x is and deleting from the array and comparing the rest of the arrays.

fun[x_, y_, v_] := Module[{a, p}, {a, p} = Delete[#, Position[x, v]] & /@ {x, y}; If[a == p, Return[True], Return[False]]]

In the above function, x is an array where there is a variable, y is an array where there are only numbers, v is the variable itself. For eg, in your case, if

a1={{0, 0, 1}, {0, 0, 1}, {0, 0, 1}}; p= {{0, 0, x}, {0, 0, 1}, {0, 0, x}}; fun[p, a1, x]
would return True.

$\endgroup$
  • $\begingroup$ I guess I was a bit too one tracked minded and didn't think of approaching it a different way. I'm happy to accept this answer unless someone gives an answer using pattern matching as I feel that it would be appropriate that way. Thanks :) $\endgroup$ – Luca Pontiggia Oct 16 '17 at 17:21

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.