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

2 次查看(过去 30 天)
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 个评论
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