matlab piece wise function

조회 수: 1 (최근 30일)
JONATHAN KATHUZA
JONATHAN KATHUZA 2019년 6월 3일
댓글: darova 2019년 6월 3일
write a matlab code that plots the following piece wise function f(t) = ( 3t^2 +5 t>0)and f(t)=(-e^t + 5t <0 )
  댓글 수: 4
JONATHAN KATHUZA
JONATHAN KATHUZA 2019년 6월 3일
편집: Rik 2019년 6월 3일
Edit Rik: copied code from attached file to comment text.
%%ploting a piecewise function
%created by Jonathan kathuza, Promise Kalonga,Christina Mkanyoza,Samuel Mboma
%Fatsani Tamandikani,Wonderful Lijoni Duwa
%02nd June 2019;
a=input('enter starting point \n');
b=input('enter end point \n');
t=a:0.01:b;
y1= -exp(t)+5;
y2=3*(t.^2)+5;
if a<0&&b<0
plot(t,y1)
xlabel('t');
ylabel('y');
elseif a>=0&&b>=0
plot(t,y2)
xlabel('t');
ylabel('y');
elseif a<0&&b>=0
plot(t,y1,'r-',t,y2,'g-')
legend('-exp(t)+5','3*(t.^2)+5;')
else
disp('invalid inputs')
end
darova
darova 2019년 6월 3일
Is there something we can help you? What is the question?

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

답변 (1개)

Rik
Rik 2019년 6월 3일
That is a good idea of solving your problem. There is one thing you're forgetting in your logic: to trim the parts you don't need in the third case. The solution to that is logical indexing, which is a good idea in the first place.
There is some code missing (because I'm not making your homework for you), but these parts should get you where you need to be.
a=-3;b=4;
if a>=b
error('invalid inputs')
end
t=a:0.01:b;
L=___
y=zeros(size(t));
y(~L)= -exp(t(~L))+5;
y(L)=3*(t(L).^2)+5;
But there is an even better solution: you can put your piecewise function in a single anonymous function and let fplot handle your problems. I'm using different conditions and functions as an example here, but you shouldn't have any trouble adapting it to your own problem.
f1=@(t)-exp(t);%function 1
f2=@(t) cos(t*5);%function 2
cond=@(t) sin(t*15)>0;%when this condition is true, set f2 to 0
f=@(t) f1(t).*cond(t) + f2(t).*~cond(t);
fplot(f,[a b])

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by