Finding difference of an array in circular manner
11 次查看(过去 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 个评论
回答(1 个)
John D'Errico
2016-11-26
d = diff(res);
d(end+1) = d(1) - d(end);
WTP?
2 个评论
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 Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!