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.

Answers (1)

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

Madhan, thanks for your response. My loop did not go to infinity but I can't seem to get N to output the exact value it reached based on the corresponding f(x) value. Perhaps this picture can help explain what I mean by this.
@Gordon number of N in my answer was 4 as you wanted
The value of N should change based on the f_min input. For example if the inputs are x=2 and f_min=15, the correct value of N should come out to N=3
For your inputs x=2 and f_min=12 , the correct value of N should be 3. Thanks again for your help.
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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Release

R2016b

Asked:

on 13 Oct 2018

Edited:

on 13 Oct 2018

Community Treasure Hunt

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

Start Hunting!