I am working on an assignment that requires me to use the trapz
function in MATLAB in order to evaluate an integral. I believe I have written the code correctly, but the program returns answers that are wildly incorrect. I am attempting to find the integral of e^(-x^2)
from 0
to 1
.
x = linspace(0,1,2000);
y = zeros(1,2000);
for iCnt = 1:2000
y(iCnt) = e.^(-(x(iCnt)^2));
end
a = trapz(y);
disp(a);
This code currently returns
1.4929e+03
What am I doing incorrectly?
答案 0 :(得分:1)
You need to just specify also the x
values:
x = linspace(0,1,2000);
y = exp(-x.^2);
a = trapz(x,y)
a =
0.7468
More details:
First of all, in MATLAB you can use vectors to avoid for-loops for performing operation on arrays (vectors). So the whole four lines of code
y = zeros(1,2000); for iCnt = 1:2000 y(iCnt) = exp(-(x(iCnt)^2)); end
will be translated to one line:
y = exp(-x.^2)
You defined x = linspace(0,1,2000)
it means that you need to calculate the integral of the given function in range [0 1]
. So there is a mistake in the way you calculate y
which returns it to be in range [1 2000]
and that is why you got the big number as the result.
In addition, in MATLAB you should use exp
there is not function as e
in MATLAB.
Also, if you plot the function in the range, you will see that the result makes sense because the whole page has an area of 1x1.