You were close. Here is one way to do what you are trying to do, keeping with the FOR loop and IF statement use.
cnt = 0;
t = -9:.5:9
for ii = t
cnt = cnt + 1;
if ii<0
y(cnt)=(3*ii.^2)+5;
else if ii>=0
y(cnt)=(-3*ii.^2)+5;
end
end
end
plot(y,t)
Here is another way, without the cnt variable.
t = -9:.5:9;
for ii = 1:length(t)
if t(ii)<0
y(ii)=(3*t(ii).^2)+5;
else if t(ii)>=0
y(ii)=(-3*t(ii).^2)+5;
end
end
end
plot(y,t)
Also, here is a more MATLABish way of doing this, for future reference:
t2 = -9:.5:9
idx = t2>=0;
y2(idx) = (-3*t2(idx).^2)+5;
y2(~idx) = (3*t2(~idx).^2)+5;
plot(y2,t2)
Best Answer