Make Matlab show number of intervals used to perform action?
3 views (last 30 days)
Show older comments
Hi everybody,
I am fairly new to Matlab, and I am currently struggling with it. I am trying to make a Simpson-integral with Matlab and making Matlab show an output with the number of intervals, n, it has used to perform the action, I made it.
Here is my script:
clear all
syms x
a=input('lowest x-value: ');
b=input('highest x-value: ');
n=input('number of intervals: '); %remember n has to be an equal number
f=input('function: ');
fx=inline(f);
m=n/2;
h=(b-a)/(2*m);
xtal=[a:h:b];
ytal=fx(xtal);
J=0;
for i=1:m
J=J+1/3*ytal(2*i-1)+4/3*ytal(2*i)+1/3*ytal(2*i+1);
end
format long
J=J*h
while abs(J-4.67077427)>0.000000001;
disp('How large a number n do you need for J to be exact with 8 decimals?')
n=2:2:100;
i=1:m;
J=0;
J=J+1/3*ytal(2*i-1)+4/3*ytal(2*i)+1/3*ytal(2*i+1);
J=J*h
if J==abs(J-4.67077427)<=0.000000001;
disp('J is exact to 8 decimals')
break
end
end
%while J<4.67077427;
%n=n+1
%end
%elseif J>4.67077427;
%disp('J is exact to more than 8 decimals')
%break
%else J<4.67077427;
%break
%end
I am currently only working with the first two sections, i.e. not with the last one after the last space. I haven't yet come to the part where I tell Matlab how to show me the number of intervals n used to let J=4.67077427+-0.000000001, because I can't make the program give me another number of J than the one given after the first section. The first section works perfectly fine, though, but the second one is a problem, because it is there I am trying to make Matlab show me the number of intervals used by the program to both give me the value of J, I showed you four lines ago and give me the lowest number of n used by the program to give me that value of J.
I hope this is sufficient. If not, please ask for more information.
Best regards, Mads
0 Comments
Answers (2)
Walter Roberson
on 15 Mar 2013
Look again at your code. You have
J==abs(J-4.67077427)<=0.000000001
That is going to be interpreted as
((J==abs(J-4.67077427)) <= 0.000000001)
the first one is going to test whether J is exactly equal to abs(J-4.67077427) . That test can only be true if J is exactly equal to (4.67077427 / 2). In that one (unlikely) case, the comparison will return 1 (true), and in all other cases the comparison will return 0 (false). You then compare that 0 or 1 to 0.000000001; that is going to result in true only if the first comparison returned 0 (false).
0 Comments
See Also
Categories
Find more on Dates and Time in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!