Storing and comparing values of an equation in loop

3 views (last 30 days)
I'm trying to run an equation f(x) for different values of x. Then I'll comapre the outputs for different values of x and return the value of x for which f(x) is maximum.
Here is the code:
i=1;
for x = 0 : 0.1 : 1
f(i) = x * exp((-2)*(x));
i= i+1;
if f(i) > f(i-1) && f(i) < f(i+1)
continue;
else
disp(x);
break;
end
end
I know there are many mistakes but this is how I imagine the code to work. Apologies for any newbie mistakes since I am an absolute begineer. Please help me.

Answers (2)

VBBV
VBBV on 1 Jan 2023
Edited: VBBV on 1 Jan 2023
syms x f(x)
f = x*exp(-2*x)
f = 
F = diff(f,x) == 0
F = 
X = 0 : 0.1 : 1;
idx = find(double(subs(F,x,X)))
idx = 6
Max = X(idx)
Max = 0.5000
plot(X,double(subs(f,x,X)))

Voss
Voss on 1 Jan 2023
Edited: Voss on 1 Jan 2023
I think this is what you're going for. Note that it's not convenient to calculate each f(i) inside the loop, because you'll need f(i+1) as well, in order to check whether f(i) is a local maximum. So you can calculate all f before the loop.
% define x
x = 0 : 0.1 : 1;
% calculate f at all x values
f = x .* exp(-2*x);
% iterate over the elements of x and f that have one before and one after
% (that is, exclude the first and last elements)
for i = 2:numel(x)-1
% local maximum condition: f(i) is greater than both f(i-1) and f(i+1)
if f(i) > f(i-1) && f(i) > f(i+1)
disp(x(i));
break;
end
end
0.5000
% a plot for verification/visualization
plot(x,f)
hold on
plot(x(i),f(i),'ro')

Categories

Find more on Line Plots 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!