Help with code: Matlab code not printing last verification line.
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (1)
Walter Roberson
le 12 Oct 2015
The "continue" is going to be executed before the fprintf() that is in the same "if"
4 commentaires
Geoff Hayes
le 12 Oct 2015
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.)
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!