One other question

Hey everyone, I just asked a few hw questions on here but I also have an exam question I'd like some help with, Its basically like this;
We need to write a program where we input a matrix and it will tell us how far into the matrix the first number out of sequence is located, so for instance if i put in:
(1,2,3,5,6) it will return 4 because the 4th spot is the first number that is not in sequence, or another ex:
(5,6,7,8,9,10,6) it will return 7 because the 7th number is not in order.
Once again, you can answer here or email me, hurry though my exams in an hour ahhh

1 Comment

Andrew Newell
Andrew Newell on 29 Mar 2011
@Mike, could you give this question a more meaningful title? An example is "How do I find a number out of sequence?"

Sign in to comment.

Answers (3)

Andrew Newell
Andrew Newell on 29 Mar 2011
Assuming your input is really a vector (as in your two examples), try using
diff(diff(vector))
and think about the output.
Something like,
find( (A(1) : A(1)+length(A) - 1) ~= A )

6 Comments

Mike
Mike on 29 Mar 2011
how would I put this into a function formula. I had something like:
function = sequence(a)
n=0
n=1+n
while a(m+1)-a(m)=x;
findx~=1
end
but it was not working obviously
Mike
Mike on 29 Mar 2011
aka i'm good at understanding kinda what i need to do, just terrible at telling the computer how to do that
function wrongidx = sequence(a)
wrongidx = find( (a(1) : a(1)+length(a) - 1) ~= a, 1 );
end
Andrew Newell
Andrew Newell on 29 Mar 2011
I hope the sequence isn't [2 4 6 8 9]!
@Andrew: see http://www.mathworks.com/matlabcentral/answers/3262-how-can-i-retrieve-common-patterns-from-a-file#comment_7867
Andrew Newell
Andrew Newell on 29 Mar 2011
That Mathematical Recreations article is great!

Sign in to comment.

Andrew Newell
Andrew Newell on 29 Mar 2011
I think a reasonable interpretation of the problem is that it is an arithmetic sequence and has to be established at the beginning before any deviations occur (so there must be at least 3 elements in the sequence first). A generalization of Walter's function to this case is then:
function wrongidx = sequence(a)
vdiff = diff(a(1:3));
if diff(vdiff)~=0,
error('There must be a sequence of at least 3 elements to start.')
end
wrongidx = find( (a(1) : vdiff(1):a(1)+vdiff(1)*(length(a) - 1)) ~= a, 1 );

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Asked:

on 29 Mar 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!