How to represent function which is defined on different interval?

I'm trying to plot function that defined on different intervals like following.
Let
phi_i(x)=M*(x-(i-1)/M) on [(i-1)/M,i/M] and M*((i+1)/M-x) on [i/M,(i+1)/M] and 0 on other values.
I got values u_1, u_2 ...u_(M-1) and note u(x)=u_1 phi_1(x)+u_2 phi_2(x) +...+u_(M-1) phi(x)
How to plot u(x)?

 채택된 답변

Rik
Rik 2018년 5월 27일
You can use a for-loop to compose the function out of the parts using anonymous functions:
phi_part_i=@(x,i) ...
M*(x-(i-1)/M)*( (i-1)/M <x & x< i/M ) + ...
M*((i+1)/M-x)*( i/M <x & x< (i+1)/M );
phi_1=@(x) phi_part_i(x,1);
phi_1_10=@(x) 0;
for m=1:10
phi_1_10=@(x) phi_1_10(x) + phi_part_i(x,m);
end

댓글 수: 7

Jinman Park
Jinman Park 2018년 5월 27일
편집: Jinman Park 2018년 5월 27일
Wow!! I've never seen code like this before!!
Thanks for your comment
Can I ask you another question?
I wrote code
j=1;
g=@(x) 0;
phi_part_i=@(x,i) N*(x-(i-1)/N)*( ((i-1)/N <x) & (x<i/N) ) + N*((i+1)/N-x)*((i/N <x) & (x<(i+1)/N));
while(j<=(N-1))
g=@(x) g(x)+u(j,1)*phi_part_i(x,j);
j=j+1;
end
fplot(@(x) g(x),@(x) sin(pi*x),[0,1])
But, I got error
> In matlab.graphics.function.ParameterizedFunctionLine>getFunction
In matlab.graphics.function.ParameterizedFunctionLine/set.XFunction
In matlab.graphics.function.ParameterizedFunctionLine
In fplot>singleFplot (line 243)
In fplot>@(f1,f2)singleFplot(cax,{f1,f2},limits,extraOpts,args) (line 201)
In fplot>vectorizeFplot (line 201)
In fplot (line 163)
In week6_1_3 (line 27)
Can you give me an advice?
phi_part_i = @(x,i) N*(x-(i-1)/N).*( ((i-1)/N <x) & (x<i/N) ) + N*((i+1)/N-x).*((i/N <x) & (x<(i+1)/N));
Thanks.
Additionally, I found another mistake that I made.
I modified last part of my code to
fplot(g(x),@(x) sin(pi*x),[0,1])
Well, I'm really sorry to ask you another one.
I wrote similar code and I followed your advice.
j=1;
g=@(x) 0;
phi_odd_i=@(x,i)-4*(N^2)*((x-((i-1)/(2*N)))*(x-((i+1)/(2*N)))).*( ((i-1)/(2*N) <x) & (x<=(i+1)/(2*N)) );
phi_even_i=@(x,i) 2*(N^2)*((x-((i-2)/(2*N)))*(x-((i-1)/(2*N)))).*( ((i-2)/(2*N) <x) & (x<=i/(2*N)) ) + 2*(N^2)*((x-((i+2)/(2*N)))*(x-((i+1)/(2*N)))).*((i/(2*N) <x) & (x<=(i+2)/(2*N)));
while(j<=(2*N-1))
if(mod(j,2)==0)
g=@(x) g(x)+u(j,1)*phi_even_i(x,j);
else
g=@(x) g(x)+u(j,1)*phi_odd_i(x,j);
end
j=j+1;
end
fplot(g,[0,1],'b')
hold on
fplot(@(x) sin(pi*x),[0,1],'r')
hold off
end
But, I face the same error. Can you give me one more advice?
Notice how I change the * operators into .* operators in my response to you before. You need to do the same thing.
Thanks.
Your advice worked!!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Time Series Events에 대해 자세히 알아보기

질문:

2018년 5월 27일

댓글:

2018년 5월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by