Today, I needed a periodical triangular function. It should have the same amplitude, phase and period like a sine. Since it seems like Matlab does not have this method included, I wrote the function myself. Here it is:

```
tri = @(x) abs(mod(x-2*pi/4,2*pi) / (pi) - 1) * 2 - 1;
```

You can later call the function as `tri(x)`

, x being a scalar, vector or matrix. This should work in Matlab and Octave.

Here is a plot showing the triangular function and the sine function:

### Short explanation

The mod-function is the key to the periodicity of the function. After \(x > 2\pi\), it starts from 0. So the output of the `mod`

-function is a sawtooth. Inside the mod-function, x is shifted by \(-\pi/2\) to be in phase with the sine.

The result of the mod function is divided by \(\pi\) since the output of the `mod`

lies between \(0\) and \(2\pi\). Shifting that down by one and calculating the absolute value yields us the desired triangular form.

If you want another periodicity, you will have to figure that out yourself. Here is the unshifted function with a period of 1.

```
tri = @(x) abs(mod(x,1)-0.5)*4-1;
```

### Bonus: Rectangular function

This one is easy. The Code might not be ideal (performance-wise), but it was the first thing I came up with when thinking about the problem:

rect = @(x) ceil(sin(x))*2 - 1;