Search code examples
matlabgraphicssimulinkmatlab-figurefigure

Randomly vary the slope of triangular wave in MATLAB?


The code below produces a triangular wave:

x=0:0.1:3;
f=(mod(x,1)<=0.3).*(1-1/0.3.*mod(x,1))+(0.3<mod(x,1)).*(1/0.7.*(mod(x,1)-0.3));
plot(x,f)

wave

I need to vary the slope (0.3 value randomly) for each cycle (1 seconds).

For example

  • 0-1 = 0.4 (random number)
  • 1-2 = 0.7 (random number)
  • .......

Solution

  • You can use rand(N,1) to get an N element column vector where each element is a random number between 0 and 1. Set N to be how ever many values are indicated by your "......." at the end of the post. As each cycle "(1 second)" increases an integer counter and use that counter to move though the random array. For example if the counter is called "count" use rand(N,1)(count) instead of "0.3".