views:

106

answers:

3

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
    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? Could someone tell me pls....

+1  A: 

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.

mtrw
Go for a vectorised version. Avoid loops in MATLAB: they're really slow.
Nzbuu
Matlab has a JIT compiler since 2003. Loops aren't that slow (although vectorised code should be used when they make things easier).
Will Robertson
+4  A: 

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);
kwatford
your answer gives different value for y(x) from my both answer...
izzat
+1  A: 

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)
Nzbuu

related questions