I am trying to write a program to solve a quadratic equation using loops and braces. see the images for the exact problem and my attempt

2 ビュー (過去 30 日間)
Here is the exact problem:
Here is my attempt:
The answers I get are: y1=5.750000e+000 and y2=-238. However, I'm not convinced by this because I should be getting more than 2 answers, shouldn't I...? i.e. for=-9:0.5:9 generates a 1x37 array. Many thanks if anyone can spot the problems!

採用された回答

Andrei Bobrov
Andrei Bobrov 2016 年 6 月 24 日
t = -9:.5:9;
n = numel(t);
out = zeros(n,1);
for jj = 1:n
if t(jj) < 0
out(jj) = 3*t(jj)^2 + 5;
else
out(jj) = -3*t(jj)^2 + 5;
end
end
or
t = (-9:.5:9)';
out = -3*sign(t).*t.^2 + 5;
  1 件のコメント
Matthew Lintern
Matthew Lintern 2016 年 6 月 24 日
Cheers for this. I solved the problem in the end and this code (Andrei Bobrov) doesn't look dissimilar to my own, so its good to see I got it in the end. Also thanks for the vectorized form! Cheers for the help.

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

その他の回答 (1 件)

Torsten
Torsten 2016 年 6 月 23 日
You get back y1, evaluated at x=-0.5, and y2, evaluated at x=9.
Do you know why ?
1. Use only one variable (y) instead of y1 and y2.
2. Save the values for t and y in an array. Otherwise (like above), you will overwrite all values previously calculated. Then plot y against t to see whether you succeeded.
Best wishes
Torsten.
  2 件のコメント
Matthew Lintern
Matthew Lintern 2016 年 6 月 23 日
I have no idea why the program only takes x=-0.5 and x=9. It just doesn't make sense to me....
Torsten
Torsten 2016 年 6 月 24 日
Now look at what the program does:
It sets t to -9 first, enters the first if-statement and sets y1 to 3*(-9)^2+5. The second if-statement is false.
In the next step, t is -8.5. Again, the program enters the first if-statement and overwrites the value for y1 obtained for t=-9 by 3*(-8.5)^2+5. The second if-statement is false.
...
In the ...-step, t is -0.5. Again, the program enters the first if-statement and overwrites the value for y1 obtained for t=-1 by 3*(-0.5)^2+5. The second if-statement is false.
In the next step, t=0. The first if-statement is false. Thus y1 keeps the value 3*(-0.5)^2+5. Now the program enters the second if-statement and sets y2 to -3*0^2+5.
In the next step, t=0.5. The first if-statement is false - y1 keeps its value 3*(-0.5)^2+5. The second if-statement is true, thus the value for y2 obtained for t=0 is overwritten by -3*(0.5)^2+5.
...
For t=9, the first if-statement is wrong. y2 keeps its value obtained for t=-0.5. The second if-statement is true. Thus the value for y2 obtained for t=8.5 is overwritten by -3*(8.5)^2+5.
Thus when the program leaves the for-loop, y1=3*(-0.5)^2+5 and y2=-3*9^2+5.
Best wishes
Torsten.

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

カテゴリ

Help Center および File ExchangeGet Started with Optimization Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by