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 views (last 30 days)
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!

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 24 Jun 2016
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 Comment
Matthew Lintern
Matthew Lintern on 24 Jun 2016
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.

Sign in to comment.

More Answers (1)

Torsten
Torsten on 23 Jun 2016
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 Comments
Torsten
Torsten on 24 Jun 2016
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.

Sign in to comment.

Categories

Find more on Function Creation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!