2

Repeating numbers with modulo

I know I can "wrap" / loop numbers back onto themselves like 2,3,1,2,3,1,... by using modulo.

Example code below.

a=[1:8]'
b=mod(a,3)+1

But how can I use modulo to "wrap" numbers back onto themselves from -1 to 1 (-1,-.5,0,.5,1). Some test numbers would be a=[1.1,-2.3,.3,-.5] it would loop around and the values would be between -1 to 1.

I guess a visual example would be bending an x,y plane from -1 to 1 into a torus (how it loops back onto itself).

Loop onto itself

I was thinking of how a sin wave goes 0,1,0,-1 and back again but I wasn't sure how I could implement it.

PS: I'm using Octave 4.2.2

Rick T
  • 3,349
  • 10
  • 54
  • 119

1 Answers1

3

This can be accomplished by offsetting the value before taking the modulo, then reversing the offset after.

For example, if the target range is [a,b) (the half-open interval such that b is not part of the interval), then one can do:

y = mod( x - a, b - a ) + a;

For example:

a = -1;
b = 1;
x = -10:0.01:10;
y = mod( x - a, b - a ) + a;
plot(x,y)
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120