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
이전 댓글 표시
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
Rik
2020년 12월 11일
What is your question? Do you want to convert your script into a function?
답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!