One other question
Afficher commentaires plus anciens
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 commentaire
Andrew Newell
le 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?"
Réponses (3)
Andrew Newell
le 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.
Walter Roberson
le 29 Mar 2011
Something like,
find( (A(1) : A(1)+length(A) - 1) ~= A )
6 commentaires
Mike
le 29 Mar 2011
Mike
le 29 Mar 2011
Walter Roberson
le 29 Mar 2011
function wrongidx = sequence(a)
wrongidx = find( (a(1) : a(1)+length(a) - 1) ~= a, 1 );
end
Andrew Newell
le 29 Mar 2011
I hope the sequence isn't [2 4 6 8 9]!
Walter Roberson
le 29 Mar 2011
@Andrew: see http://www.mathworks.com/matlabcentral/answers/3262-how-can-i-retrieve-common-patterns-from-a-file#comment_7867
Andrew Newell
le 29 Mar 2011
That Mathematical Recreations article is great!
Andrew Newell
le 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 );
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!