"for" loops and branching help

5 ビュー (過去 30 日間)
Kyle
Kyle 2011 年 3 月 2 日
I'm having trouble solving this question: Write the MATLAB statements required to calculate y(t) from the equation y(t) = -3*t^2 + 5 when t>=0
y(t) = 3*t^2 + 5 when t<0
for the values of t between -9 and 9 in steps of .5. Use loops and branches to solve
Heres what i have;
for t = -9:.5:9
if t<0
y=(3*t.^2)+5;
else if t>=0
y=(-3*t.^2)+5;
end
end
end
plot(y,t)
I know Im missing something, like maybe count=0; and count = count + 1 but I've tried it still was unsuccessful

採用された回答

Matt Fig
Matt Fig 2011 年 3 月 2 日
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)

その他の回答 (1 件)

Paulo Silva
Paulo Silva 2011 年 3 月 2 日
t=-9:0.5:9;
y=0*t;
y(t<0)=3*t(t<0).^2+5;
y(t>=0)=-3*t(t>=0).^2+5;
Here's another way
t=-9:0.5:9;
y=sign(t).*3.*t.^2+5;
PS: I know the OP wants loops but I couldn't resist :)
  2 件のコメント
Matt Tearle
Matt Tearle 2011 年 3 月 3 日
Yes. Logical indexing > loops + branching. All bow before the logical index!!!
Paulo Silva
Paulo Silva 2011 年 3 月 3 日
Yeah, baby, yeah!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by