Storing and comparing values of an equation in loop
3 views (last 30 days)
Show older comments
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:
for x = 0 : 0.1 : 1
f(i) = x * exp((-2)*(x));
if f(i) > f(i-1) && f(i) < f(i+1)
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.
VBBV on 1 Jan 2023
Edited: VBBV on 1 Jan 2023
syms x f(x)
f = x*exp(-2*x)
F = diff(f,x) == 0
X = 0 : 0.1 : 1;
idx = find(double(subs(F,x,X)))
Max = X(idx)
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)
% a plot for verification/visualization
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!