If statement within a while loop within a function to find min f(x) value reached?
이전 댓글 표시
How can I create a UDF which accepts input values for x and a minimum f(x) value to be reached and calculates the value of f(x) by adding just enough terms to reach the minimum f(x) value which is specified by the input variables and returns the minimum value of N that is required to reach the minimum value specified by the input variables? The function i'm working with is f(x)=\sum_{k=0}^{k=N}x^k such that f(x)=1+x+x^2+x^3+...+x^N
Here is the code I've attempted for this problem
function [N]=myfxterms(x,f_min)
N=0;
f=0;
while f<f_min
f=f+x^N;
if f<=1
N=0;
else
N=N+1;
end
disp(N)
end
I can't seem to make the counter N stop whenever the specific minimum value of f(x) is reached. Any help on this problem would be greatly appreciated. Thanks.
답변 (1개)
madhan ravi
2018년 10월 13일
편집: madhan ravi
2018년 10월 13일
x=2
f_min=12
N=myfxterms(x,f_min)
function [N]=myfxterms(x,f_min)
N=0;
f=0;
while f<f_min
f=f+x^N;
if f<=1 N=0;
else N=N+1;
end
end
disp(N)
end
My loop stopped but it didn’t go to infinity as you stated.
댓글 수: 5
Gordon Smith
2018년 10월 13일
madhan ravi
2018년 10월 13일
@Gordon number of N in my answer was 4 as you wanted
Gordon Smith
2018년 10월 13일
편집: Gordon Smith
2018년 10월 13일
Gordon Smith
2018년 10월 13일
madhan ravi
2018년 10월 13일
x =
2
f_min =
15
f =
1
f =
2
f =
4
f =
8
f =
16
4
N =
4
>>
As you can see the loop stopped at f<15 thats why the N is 4 instead of 5 , so the formula you are using maybe wrong but the code conditions are satisfied without any doubts
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!