Is there an efficient way to write a piecewise function ?

3 visualizzazioni (ultimi 30 giorni)
Hi,
I have a very long 1 x 4000 temperature vector, A = [a1 a2 a3 a4 a5 a6 a7 .... a4000].
I also have the hours vector T = [t1 t2 t3 t4 t5 .....t4000]. A and T are given.
Now, I wish to have a stair function, such that,
if 0<=t<t1 func = a1;
if t1<=t<t2 func = a2;
if t2<=t<t3 func = a3;...
In the stuff I am doing, I used to use "piecewise" function for small number of A and T for testing (maybe just a1 to a10). So, I can manually wrote pieces one by one. Now, I need to use the real stuff A,which is very long. I cant do this one by one anymore. So, my question is, is there a way I could make a piecewise stair function for given A and T.
Please do notice that:
  1. This stair function will be feed into integration later. It must be ONE function, that's why I was using "piecewise" (It works well). In other words, I do NOT use it just for plot.
  2. Honestly, I dont know this piecewise function will allow me to manually write that many pieces to a4000 or not.

Risposta accettata

Star Strider
Star Strider il 24 Ago 2021
The condition statements wr.t. ‘t’ need to be revised slightly, and with that change, this works:
t1 = 5;
t2 = 7;
t3 = 15;
a1 = @(t) sin(t);
a2 = @(t) 5;
a3 = @(t) cos(t);
func = @(t) a1(t).*(0<=t & t<t1) + a2(t).*(t1<=t & t<t2) + a3(t).*(t2<=t & t<t3);
tv = linspace(-5,20);
figure
plot(tv, func(tv))
grid
Note — While all the ‘a’ values are functions of ‘t’ for simplicity, they can be constants.
.

Più risposte (1)

Bruno Luong
Bruno Luong il 24 Ago 2021
tempfun = @(x) interp1([0 T], A([1:end end]), x, 'previous');
temp = tempfun(whatever_query_t);

Categorie

Scopri di più su Mathematics in Help Center e File Exchange

Tag

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by