Finding difference of an array in circular manner

7 Ansichten (letzte 30 Tage)
BlueBee77
BlueBee77 am 26 Nov. 2016
Bearbeitet: Stephen23 am 26 Nov. 2016
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 Kommentar
Stephen23
Stephen23 am 26 Nov. 2016
Bearbeitet: Stephen23 am 26 Nov. 2016
@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 [].

Melden Sie sich an, um zu kommentieren.

Antworten (1)

John D'Errico
John D'Errico am 26 Nov. 2016
d = diff(res);
d(end+1) = d(1) - d(end);
WTP?
  2 Kommentare
BlueBee77
BlueBee77 am 26 Nov. 2016
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 am 26 Nov. 2016
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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by