Is there an efficient way to write a piecewise function ?

조회 수: 5 (최근 30일)
sun
sun 2021년 8월 24일
댓글: Star Strider 2021년 8월 25일
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.

채택된 답변

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);
figure
plot(tv, func(tv))
grid
Note — While all the ‘a’ values are functions of ‘t’ for simplicity, they can be constants.
.

추가 답변 (1개)

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

카테고리

Help CenterFile Exchange에서 Parallel Computing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by