Help with code: Matlab code not printing last verification line.

조회 수: 1 (최근 30일)
Tyw7
Tyw7 2015년 10월 12일
댓글: Geoff Hayes 2015년 10월 12일
I can't get Matlab to print the last "data within tolerance" line:
function [integral] = intmidpoint(N)
clear
clc
%INTMIDPOINT numerical integration using the composite midpoint rule
clc
%define the integration limits
a=0;
b=2;
%this is the aim of absolute error required
aim = 0.001;
%define the number of sub-intervals to be used
if nargin == 1
n=N;
else
n=1;
end
h=(b-a)/n;
%approximate integral using the composite mid-point rule
integral=0.0;
%add the contribution of each sub-interval in turn
abs_err = realmax;
while abs_err>aim;
h=(b-a)/n;
integral=0.0;
for i=1:n;
x_left = a+(i-1)*h;
x_right = a+i*h;
x_half = (x_left+x_right)/2.0;
f_half = f(x_half);
integral = integral+h*f_half;
abs_err=abs(4-integral);
end;
fprintf('2 Midpoint approximation to integral using %g subintervals is %g. \n Data outside of tolerance. Abosolute error is %g, which is greater than 0.001. Increase the number of steps. \n',n,integral,abs_err);
n = n + 1;
if abs_err>aim;
continue;
fprintf('test Midpoint approximation to integral using %g subintervals is %g. \n Data within tolerance. Absolute error is %g, which is less than 0.001. \n',n,integral,abs_err);
end;
end;
end
%subfunction defines the integrand
function [f_value] = f(x)
f_value = (x)^3;
end

답변 (1개)

Walter Roberson
Walter Roberson 2015년 10월 12일
The "continue" is going to be executed before the fprintf() that is in the same "if"
  댓글 수: 4
Walter Roberson
Walter Roberson 2015년 10월 12일
You want break rather than continue
Geoff Hayes
Geoff Hayes 2015년 10월 12일
Try this
if abs_err>aim
fprintf('test Midpoint approximation to integral using %g subintervals is %g. \n Data within tolerance. Absolute error is %g, which is less than 0.001. \n',n,integral,abs_err);
break;
end
Note that the
ans =
3.9990
is the output parameter returned from your function call. You are probably calling your function from the command line without assigning the output to a variable. Try calling your function as
[estIntegral] = intmidpoint(42);
to suppress the extra output. (Note that it is the use of the semi-colon that is suppressing the output.)

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by