Writing a piecewise function.

19 ビュー (過去 30 日間)
Bgr Mrt
Bgr Mrt 2017 年 11 月 28 日
回答済み: Walter Roberson 2017 年 11 月 28 日
Hello My teacher gave me a piecewise function to write on MATLAB.But i am not allowed to use loops like else/if/while.I tried to write something and i managed to made it. Are there any efficient way to write piecewise function? The codes that i write :
function BugraMrt(varargin)
t1=varargin{1}
A=varargin{2}
T=varargin{3}
t=-2:0.1:t1;
x1=(((-A.^2).*(t.^3))./(6*T.^2))+(((A.^2).*(t.^2))./(2*T));
x2=(((A.^2).*((t-T).^3))./(6*T.^2))-(((A.^2).*t)./2)+((5*(A.^2).*T)./6);
v = @(t) [(x1).*((0<=t) & (t<T)) + (x2).*((T<=t) & (t<2*T))];
figure
vt = v(t);
plot(t,vt);
ylabel('S(\tau)')
xlabel('\tau')
the Second code i write is:
function Bugrahan(varargin)
t1=varargin{1}
A=varargin{2}
T=varargin{3}
t=-2:t1:1;
x1=(((-A.^2).*(t.^3))./(6*T.^2))+(((A.^2).*(t.^2))./(2*T));
x2=(((A.^2).*((t-T).^3))./(6*T.^2))-(((A.^2).*t)./2)+((5*(A.^2).*T)./6);
y=piecewise(t<=0, 0, (0<=t)&&(t<=T), x1,(T<=t)&&(t<=(2*T)),x2,t>=(2.*T),0);
figure
plot(t,y)
is there any way to improve this code? If i did mistakes can you tell my mistakes? Thank you for your help. Have a Good Day.

採用された回答

Walter Roberson
Walter Roberson 2017 年 11 月 28 日
Your teacher probably expects you to use logical indexing.
y = nan(size(t));
mask = t < 0;
y(mask) = 0;
mask = ...
y(mask) = x1(mask);
...

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStair Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by