Loop to evaluate consecutive values in array

  • 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
Reply M 4/29/2010 8:20:24 PM

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
Reply dpb 4/29/2010 8:32:19 PM


"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
Reply Roger 4/29/2010 8:48:04 PM

"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
Reply us 4/29/2010 9:02:04 PM

3 Replies
362 Views

(page loaded in 0.026 seconds)

Similiar Articles:













7/22/2012 4:06:23 PM


Reply: