My for loop is suppose to return the minimum value found in the for loop, but it just keeps returning the last found value. How can I make it return the minimum value found?
This is my code:
function m=myminimum (f,a,b);
syms x ;
for t=(a:b);
m=subs(f(x),t);
end
m=min(m);
end
Here is some sample data I have been running through the for loop along with what the answer it's suppose to be.
myminimum(@(x) x^2+1,-3,2)
ans =
1
The answer my for loop provides is 5.
myminimum(@(x) x^2+6*x-3,-2,0)
ans =
-11
The answer my for loop provides is -3.
How do I make my for loop return the minimum value of the for loop and not just the last found value?
Thanks

 채택된 답변

Star Strider
Star Strider 2014년 10월 4일

0 개 추천

You need to tweak your loop a bit:
syms x
min_m = Inf;
for t=(a:b);
m=subs(f(x),t);
min_m = min(m, min_m);
end
m=min_m;
It initially sets ‘min_m’ to Inf, then in each iteration compares the current value of ‘m’ with the previous value and assigns ‘min_m’ to the minimum value of that comparison. It returns that value as ‘m’.

댓글 수: 4

Bri
Bri 2014년 10월 4일
편집: Bri 2014년 10월 4일
That did not work, the for loop is still returning 5 and -3 as the answers for the sample data. Not 1 and -11, like it is suppose to.
Star Strider
Star Strider 2014년 10월 4일
Strange indeed. It worked for me or I’d not have posted it.
Post the code you have now.
Bri
Bri 2014년 10월 4일
Thanks, I had a typo. And figured it out as I was putting my code into this comment.
Star Strider
Star Strider 2014년 10월 4일
편집: Star Strider 2014년 10월 4일
My pleasure!
I was getting worried.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

Bri
2014년 10월 4일

편집:

2014년 10월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by