MATLAB Answers

Is there an efficient way to write a piecewise function ?

2 ビュー (過去 30 日間)
sun 2021 年 8 月 24 日
コメント済み: Star Strider 2021 年 8 月 25 日
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.


Star Strider
Star Strider 2021 年 8 月 24 日
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);
plot(tv, func(tv))
Note — While all the ‘a’ values are functions of ‘t’ for simplicity, they can be constants.
  2 件のコメント
Star Strider
Star Strider 2021 年 8 月 25 日
As always, my pleasure!


その他の回答 (1 件)

Bruno Luong
Bruno Luong 2021 年 8 月 24 日
tempfun = @(x) interp1([0 T], A([1:end end]), x, 'previous');
temp = tempfun(whatever_query_t);
  1 件のコメント
sun 2021 年 8 月 25 日
thank you



Community Treasure Hunt

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

Start Hunting!

Translated by