Piecewise functions in MATLAB. Help!

590 Views Asked by At

I am trying to plot a pretty repetitive function in MATLAB. The values of $f$ are the same each $y$ for a designated season in the year. We have a function $f(t)$ and:

$$ f(t) = \begin{cases} 500 & \text{ if } 0 \le x < 91 \\ 1500 & \text{ if } 91 \le x < 182 \\ 500 & \text{ if } 182 \le x < 273 \\ 0 & \text{ if } 273 \le x < 365 \end{cases} $$

I am able to plot this for one year using a piecewise function. But I am wondering how to extend this further. What if I want to plot this for a period of ten years, without having to manually input the values of $t$? Is there something that I can use, like an elseif function? I am quite confused on how to do this.

So far, I have been using a piecewise function and manually inputting the values of $t$ is getting very tedious.

For example, I have:

$f = {\tt piecewise}(0 \le t<91,500,91 \le t<182,1500,182 \le t<273,500,273 \le t<365,0,365 \le t<456,500,456 \le t<547,1500,547 \le t<638,500,638 \le t<730,0,730 \le t<821,500,821 \le t<912,1500,912 \le t<1003,500,1003 \le t<1095,0); $

Just wondering if there is an easier way to do this. Thank you so much!

2

There are 2 best solutions below

1
On

It can be useful to represent your function analytically as a sum of functions each of which has a factor of a "Heaviside function". This is standard in the use of Laplace transforms in differential equations, for instance. For example your function can be written as $500+1000\theta(x-91)-1000\theta(x-182)-500\theta(x-273)$, where $\theta(x)$ is the Heaviside function. (It may take some work to ensure that you have the desired behavior exactly at each "transition point", if you care about that.) This is not essential to what you're trying to do if you already have the piecewise function defined for a single period in another way.

Once you have your function f defined for one period, taking the periodic extension is as simple as considering f(mod(x,365)) (in Matlab notation). Most other programming languages (C,Python,...) use an operator % instead of a function "mod", so you would write f(x%365) in such languages.

0
On

It looks like you have 12 segments, so I'd make an input num_segments=12; and an input t_length=92; as finally an array y_result=[500,1500,500,0]; (and so on). Then, in your function, you have, say, a for loop, with i=0:num_segments-1 and then on each iteration, programmatically define t_lengthi<=t(i+1) and extract y_result[i]. Does that help?

I apologize for the bad formatting and if my syntax is wrong on defining arrays. I work in multiple languages and always forget which one uses brackets vs. parentheses for different things.