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:
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.
0 Comments
Answers (2)
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
% a plot for verification/visualization
plot(x,f)
hold on
plot(x(i),f(i),'ro')
0 Comments
See Also
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!