beginner question :subject : For loops , while loops , index variable

3 ビュー (過去 30 日間)
Marco jacome
Marco jacome 2013 年 3 月 13 日
Write a 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
The values of t between -9 and 9 in steps of 0.5. (Use loops and branches)
??????????????is this correct ?????????????????????????
OR DO I HAVE TO PRE-ALLOCATE TIME (t) before I START THE LOOP
my program:
t = -9:0.5:9; % initialize the control expression
for ii = 1:length(t)
if t(ii) >= 0
y = -3*t.^2 + 5;
else
y = 3*t.^2 + 5;
end
end
if true
  2 件のコメント
Walter Roberson
Walter Roberson 2013 年 3 月 13 日
The "if true" at the end is a mistake.
Marco jacome
Marco jacome 2013 年 3 月 13 日
Thanks walter. I forgot to delete the bottom line.

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

回答 (3 件)

Walter Roberson
Walter Roberson 2013 年 3 月 13 日
When you display "y" afterwards, is the number of values the same as the number of values in "t" ?

Carlos
Carlos 2013 年 3 月 13 日
編集済み: Carlos 2013 年 3 月 13 日
This is what I would do:
for k=1:length(t)
if t(k)<=0
y4(k)=3*t(k)^2 + 5;
else
y4(k)=-3*t(k)^2 + 5;
end
end
You don't need the point after t here y = -3*t.^2 + 5;
Compare with the answer with no loops and branches
>> t2=0:0.5:9;
>> y2=-3*t2.^2 + 5;
>> t1=-9:0.5:-0.5;
>> y1=3*t1.^2 + 5;
>> y=[y1 y2];
>> isequal(y,y4)
ans =
1

Marco jacome
Marco jacome 2013 年 3 月 13 日
Thanks Carlos and Walter , but it is still not clear to me... nonetheless, your advice helps alot. I just have to practice a lil bit

カテゴリ

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