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
Andrew Newell
2011년 3월 29일
@Mike, could you give this question a more meaningful title? An example is "How do I find a number out of sequence?"
답변 (3개)
Andrew Newell
2011년 3월 29일
Assuming your input is really a vector (as in your two examples), try using
diff(diff(vector))
and think about the output.
Walter Roberson
2011년 3월 29일
Something like,
find( (A(1) : A(1)+length(A) - 1) ~= A )
댓글 수: 6
Mike
2011년 3월 29일
Mike
2011년 3월 29일
Walter Roberson
2011년 3월 29일
function wrongidx = sequence(a)
wrongidx = find( (a(1) : a(1)+length(a) - 1) ~= a, 1 );
end
Andrew Newell
2011년 3월 29일
I hope the sequence isn't [2 4 6 8 9]!
Walter Roberson
2011년 3월 29일
@Andrew: see http://www.mathworks.com/matlabcentral/answers/3262-how-can-i-retrieve-common-patterns-from-a-file#comment_7867
Andrew Newell
2011년 3월 29일
That Mathematical Recreations article is great!
Andrew Newell
2011년 3월 29일
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 );
카테고리
도움말 센터 및 File Exchange에서 MATLAB에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!