1
$\begingroup$

Given a sorted table, how can I find the position of non consecutive numbers in the first column of the table?

list = {{1, 3, 5}, {3, 3, 5}, {4, 3, 5}, {5, 3, 5}, {7, 3, 5}}//MatrixForm

enter image description here

How to do I find the row position of the first non-consecutive number in column one?
How to do I find the row position of the last non-consecutive number in column one?

$\endgroup$
0

2 Answers 2

5
$\begingroup$

I would rather define:

list = {{1, 3, 5}, {3, 3, 5}, {4, 3, 5}, {5, 3, 5}, {7, 3, 5}};

If you prefer for some reasons your own definition you can use list[[1]] instead of list. To extract the first column use First@Transpose@list or list[[All, 1]], for the last column use Last@Transpose@list, for k-th column e.g. list[[All, k]].

Then there are many ways, let's show a few of them:

Position[ KroneckerDelta /@ (Differences[ First @ Transpose @ list] - 1), 0] + 1
{{2}, {5}}

Instead of mapping KroneckerDelta we could use simply Unitize (as pointed out by J.M.), since it is Listable. Moreover we could substitute Differences with subtruction of Rest and Most to get the proper result:

Position[ Unitize[ Subtract @@ Through@{Rest, Most}@First@Transpose@list - 1], 1] + 1

another method without Apply for extracting non-consecutive numbers of the last column:

Position[ Total[ Through @ { Rest, - Most @ # &} @ Last @ Transpose @ list], 0] + 1
 {{2}, {3}, {4}, {5}}

A related discussion useful for the problem at hand you can find reading answers to this question Find zero crossing in a list.

$\endgroup$
4
  • 4
    $\begingroup$ Alternatively: Position[Unitize[Differences[list][[All, 1]] - 1], 1] + 1 $\endgroup$ Commented Jun 1, 2013 at 13:32
  • $\begingroup$ OK. . .I like the last answer. . .So the first non-consecutive will be: result[[1]]. . .The last non-consecutive: result[[Length[result]]] $\endgroup$ Commented Jun 4, 2013 at 9:14
  • $\begingroup$ How to upvote to the answer given by 0x4A4D? $\endgroup$ Commented Jun 4, 2013 at 12:30
  • $\begingroup$ @HpRadojewskiSchäferVon There is one way: Answer your question with his answer and then accept it. Another way: try to convince him to write that answer. Than you'll be able to upvote an accept his answer. $\endgroup$
    – Artes
    Commented Jun 4, 2013 at 15:00
2
$\begingroup$

EDIT

My original code was padding with 0 was specific for test not general...apologies.

In the test example the position of the non-consecutive numbers in the first clumn are 2 and 5 (correct me if I am misinterpreting).

Applying:

fun[u_List] := 
 Position[Differences@PadLeft[u, Length@u + 1,u[[1]]-1], _?(# > 1 &)]

to the first column finds positions of element whose preceding element is > 1.

i.e.

fun[list[[;;,1]]]

yields:

{{2}, {5}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.