Approximation of integers and forming a table

조회 수: 1 (최근 30일)
Benjamin Trivers
Benjamin Trivers 2020년 2월 2일
답변: John D'Errico 2020년 2월 2일
function:
function y=func(x)
y=sqrt(4x^2);
end
The midpoint rule:
function y=Mid(a,b,N)
dx=(b-a)/N;
y=0;
for i=1:N
y=y+func(a+(i-0.5)*dx)*dx;
end
end
The trapezoidal rule:
function y=Trap(a,b,N)
dx=(b-a)/N;
y=0;
for i=1:N
y=y+0.5*(func(a+(i-1)*dx) + func(a+i*dx))*dx;
end
end
Simpson’s Rule:
function y=Simp(a,b,N)
dx=(b-a)/N;
y=0;
for i=1:N
y=y+(1/6)*(func(a+(i-1)*dx) + 4*func(a+(i-0.5)*dx) + func(a+i*dx))*dx;
end
end
Question:
IN MATLAB ONLY
Using these four functions, create a script to publish, writing a cell that uses N=10,20,40,80,160,320 to calculate the approximations to the integral below using each of the three rules. The script should calculate the values as well as the absolute errors for each rule and display them in a nicely formatted table, which should include the method, N, the approximate value, and the absolute error. To format the table, use
fprintf('\%s | \%s | \%s | \%s \\n','N','Method','Value','AbsError')
Can't figure out how to run a loop for each different N and to put it in a table
  댓글 수: 3
Benjamin Trivers
Benjamin Trivers 2020년 2월 2일
its because i cant find my original post for this
John D'Errico
John D'Errico 2020년 2월 2일
It was there. I've closed it now, because it added nothing, as a duplicate question.

댓글을 달려면 로그인하십시오.

답변 (1개)

John D'Errico
John D'Errico 2020년 2월 2일
Just use a loop. You already seem to know how to use a loop.
a = ... % whatever
b = ... % whatever
Nlevels = [10,20,40,80,160,320];
for nind = 1:numel(Nlevels);
N = Nlevels(nind);
ymid_ind = Mid(a,b,N);
fprintf(...)
end
You can do the same for each rule, looping over the various N.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by