Finding difference of an array in circular manner

13 次查看(过去 30 天)
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