开发者

MATLAB and function

I want to calculate the function y(t) from the equation:

y(t) = -3t^2+5, t>=0
y(t) = 3t^2+5, t<0

for -9 <= t <= with the step-size 0.5

And I want to plot it by using MATLAB. I approach this question in two ways:

First

t=0:0.5:9
y=-3*t^2+5

t1=-0.00000000001:0.5:-9
y1=3*t^2+5

plot(t,y,t1,y1)

Second by using loop

t=-9:0.5:9

if(t>=0)
    y=-3*(t.^2)+5
else
  开发者_JS百科  y=3.*(t.^2)+5
end

plot(t,y)

My problem is the two ways above seem not to give the same answer... Which one is the correct answer?


You can use the sign function to do this particular example a little easier:

t = -9:0.5:9;
y = -sign(t)*3.*t.^2 + 5;
plot(t,y);


In your first attempt, your t1 definition should be:

t1 = 0:-0.5:-9;

Note the minus sign on the increment.

Using a "loop" you seem to have left out the actual loop part. Try something like

t = -9:0.5:9;
for idx = 1:length(t)
    if t(idx) <= 0
        y(idx) = -3*(t(idx).^2)+5

etc.


Here's a more idiomatic solution that avoids SIGN for cases where that's not the only difference.

t = -9:0.5:9
y = -3*t.^2+5
y(t<0) = 3*t(t<0).^2+5

plot(t, y)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜