필터 지우기
필터 지우기

Finding difference of an array in circular manner

조회 수: 11 (최근 30일)
BlueBee77
BlueBee77 2016년 11월 26일
편집: Stephen23 2016년 11월 26일
I am working on a vector res= {6,28,158,224,303,307,311,316,501,715} and finding differences of each elements. If the difference is less than 40, find the average of two values and move to next value. The current code does that. I want to update the code so that it can find the difference of the last and first value and if its less than suppose 40 find the average of them. The current code is:
d = diff( res );
idx = find( d < 40 );
res( idx ) = ( res( idx ) + res( idx + 1 ) ) / 2;
res( idx + 1 ) = [];
I would appreciate if anyone can help.
  댓글 수: 1
Stephen23
Stephen23 2016년 11월 26일
편집: Stephen23 2016년 11월 26일
@BlueBee77: are you really defining the vector as a cell array, using curly braces?:
res= {6,28,158,224,303,307,311,316,501,715}
Your code (and any reasonable solutions) will only make sense if defining a numeric vector using square brackets [].

댓글을 달려면 로그인하십시오.

답변 (1개)

John D'Errico
John D'Errico 2016년 11월 26일
d = diff(res);
d(end+1) = d(1) - d(end);
WTP?
  댓글 수: 2
BlueBee77
BlueBee77 2016년 11월 26일
Thanks for replying. Yes,i know that. I think i didnt explain in the question, i am finding the difference of the elements including the first and last, and if the differences less than 40, i want an average of those two values.
John D'Errico
John D'Errico 2016년 11월 26일
What I showed for the end point is completely valid, as far as your question is concerned.
Your "algorithm" will fail though, because of what I call a transitivity problem. Consider the vector:
v = 0:39:1000;
EVERY element is within 40 of its neighbors. If you use diff and find however, it finds everything. You need to decide what you will do there.
You have described a sequential operation, that works from the left end upwards. But your code does not work sequentially. So you need to decide on an explicit scheme. That is your real problem, that you described something with a vague set of words. When you want to write code, you need to be clear, accurate, complete.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by