If statement within a while loop within a function to find min f(x) value reached?
Show older comments
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.
Answers (1)
madhan ravi
on 13 Oct 2018
Edited: madhan ravi
on 13 Oct 2018
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 Comments
Gordon Smith
on 13 Oct 2018
madhan ravi
on 13 Oct 2018
@Gordon number of N in my answer was 4 as you wanted
Gordon Smith
on 13 Oct 2018
Edited: Gordon Smith
on 13 Oct 2018
Gordon Smith
on 13 Oct 2018
madhan ravi
on 13 Oct 2018
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
Categories
Find more on Loops and Conditional Statements 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!