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
    조회 수: 4 (최근 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!
댓글 수: 0
채택된 답변
  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개)
  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
  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 Exchange에서 Function Creation에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


