COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### Loop to evaluate consecutive values in array

• Email
• Follow

I'm new to Matlab and still unsure as to how to create loops.  I want to make a loop that will run through each value in the array and compare consecutive values.  If the difference between consecutive values is greater than pi, I want to add 2*pi to the second value.  If the difference between consecutive values is less than -pi I want to subtract 2*pi from the second value.  How might I go about doing this?

Thank you!
 0

See related articles to this posting

M.E.L. wrote:
> I'm new to Matlab and still unsure as to how to create loops.  I want to
> make a loop that will run through each value in the array and compare
> consecutive values.  If the difference between consecutive values is
> greater than pi, I want to add 2*pi to the second value.  If the
> difference between consecutive values is less than -pi I want to
> subtract 2*pi from the second value.  How might I go about doing this?

You don't need loops most of the time in Matlab--that's the beauty of it...

x = some_values;
dx = diff(x);  % sequential differences
idx1 = find(dx>pi);
x(idx1) = x(idx1+1)+2*pi;

idx2 = find(dx<-pi);
x(idx2) = x(idx2+1)-2*pi;

You may have to do this repetitively, however...

--

 0

"M.E.L. " <schrodingers.lyon@gmail.com> wrote in message <hrcpm8\$def\$1@fred.mathworks.com>...
> I'm new to Matlab and still unsure as to how to create loops.  I want to make a loop that will run through each value in the array and compare consecutive values.  If the difference between consecutive values is greater than pi, I want to add 2*pi to the second value.  If the difference between consecutive values is less than -pi I want to subtract 2*pi from the second value.  How might I go about doing this?
>
> Thank you!

There is a matlab function called 'unwrap' which will do that whole job for you in one line.

xnew = unwrap(xold);

Roger Stafford
 0

"M.E.L. " <schrodingers.lyon@gmail.com> wrote in message <hrcpm8\$def\$1@fred.mathworks.com>...
> I'm new to Matlab and still unsure as to how to create loops.  I want to make a loop that will run through each value in the array and compare consecutive values.  If the difference between consecutive values is greater than pi, I want to add 2*pi to the second value.  If the difference between consecutive values is less than -pi I want to subtract 2*pi from the second value.  How might I go about doing this?
>
> Thank you!

just want to make sure you'll also look at these

help for;
help while;
help end;

us
 0