I am having problems changing this code so that it includes FUNCTION in Matlab. I made the code so takes one specific equation but need it edited so it takes any equation. EDIT CODE SO THAT USES FUNCTION IN MATLAB
Show older comments
Let the function is f(x) = 8 - x^2
f = @(x) 8-x.^2;
% Let us take a Riemann sum over [-2,2] at dx =0.5
dx=0.5;
x=-2:dx:2;
R_sum =0;
for i=1:length(x)
R_sum = R_sum + f(x(i)+dx/2)*dx; % Mid point Riemann sum
end
display(R_sum)
% Let us apply Trapezoidal rule over [-2,2] at dx =0.5
T_sum = 0;
for i=1:length(x)-1
T_sum = T_sum + (f(x(i+1))+f(x(i)))*dx/2;
end
display(T_sum)
figure(1)
grid on
hold on
bar(x,f(x),1,'y'); %ploting rectangles for Riemann sum
hold on
xp=-2:0.01:2; %ploting the function
plot(xp,f(xp),'b')
figure(2)
grid on
hold on
% ploting the trapezoids
for i=1:length(x)
plot([x(i),x(i)],[0,f(x(i))],'r'); % Ploting the vertical lines
hold on
end
for i=1:length(x)-1
% Ploting the non-parallal lines
plot([x(i+1),x(i)],[f(x(i+1)),f(x(i))],'r')
hold on
end
xlim([min(x)-0.5,max(x)+0.5])
hold on
plot(xp,f(xp),'b') %ploting the function
1 Comment
Rik
on 11 Dec 2020
What is your question? Do you want to convert your script into a function?
Answers (0)
Categories
Find more on Programming 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!