So, in principle, I have a simple problem which goes like this: I have vectors that should consist of lists of 2 numbers, see here:
vector1 = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {1198, 800}, {1199 799}, {1200, 799}, {0, 0}, {0, 0}, {0, 0}};
Unfortunately, sometimes they do not have this structure, but are mixed like in here, where the parenthesis are missing around 1200,800 and the following 0,0:
vector2 = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, 1200, 800, 0, 0, {0, 0}, {0, 0}, {0, 0}};
My current solution is to use While with If inside, to create a new list with the correct structure:
correctVectorPattern[inputVector_] :=
Module[{i = 1, newVector = {}},
While[i <= Length[inputVector],
If[Length[inputVector[[i]]] ==2, {AppendTo[newVector,inputVector[[i]]],i++}, {AppendTo[newVector, {inputVector[[i]], inputVector[[i + 1]]}], i = i + 2}]
];
newVector
]
It gives me what I want:
In[39]:= correctVectorPattern[vector1]
Out[39]= {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {1198, 800}, {1199,799}, {1200, 799}, {0, 0}, {0, 0}, {0, 0}}
In[36]:= correctVectorPattern[vector2]
Out[36]= {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {1200, 800}, {0,0}, {0, 0}, {0, 0}, {0, 0}}
But I can't shake off the feeling that my solution is far from the capabilities of Mma regarding pattern matchin in expressions. Also, I am using If, While and AppendTo, which are probably not the fastest functions for solving my problem. Unfortunately, the vectors are at least 1200 elements long and I need to process 800 of them (these dimensions are due to the size of images I get the vectors from - of 1200 x 800). On my machine it takes me about 14 s, which is not that long, but I would like to scale it up to 5000 x 3000 pixels. Of course Parallel processig or Compiling are also possible and easy options, but with Mma pattern capabilities - shouldn't the solution be something of a 1-liner?
I tried of course myself to solve problem by exploiting patterns, but I end up processing all of the elements in the same way. So I simply don't know how to tell MMa to group elements inside the list that are whithout parenthesises into 2-tuples, while keeping the other 2-tuples..
Does somebody have a more elegant or faster solution to my problem? Thanks a lot!
(And should you wonder why I ask, even though I have working solution: .. a better understanding of Mma doesn't hurt at all ;-) )