double integral using trapz

I'm trying to approximate a double integral using traps. This code is telling me the answer is 0 when it should be pi/4. I'm not sure how to fix it.
clear; close all; clc;
x = 0:.1:1;
y = 0:.1:sqrt(1-x.^2);
[X,Y] = meshgrid(x,y);
F = 1;
I = trapz(x,trapz(y,F));

回答(2 个)

Walter Roberson
Walter Roberson 2015-5-18

1 个投票

0:.1:sqrt(1-x.^2) with x a vector, tries to use a vector as the termination value for the iteration. When the termination value is a vector, only the first element of the vector is used. Your y is thus the same as
0:.1:sqrt(1-x(1).^2)
and your x and y are both linear -- actually they are even the same. Nothing much to integrate.

3 个评论

Thanks for the response!
This is the integral I'm trying to evaluate. When I try this
clear; close all; clc;
x = 0:.1:1;
y = 0:.1:sqrt(1-x^2);
[X,Y] = meshgrid(x,y);
F = 1;
I = trapz(x,trapz(y,F));
I get an error
Error using ^
Inputs must be a scalar and a square matrix.
To compute elementwise POWER, use POWER (.^) instead.
Error in callman_7_1 (line 3)
y = 0:.1:sqrt(1-x^2);
You are still trying to use a vector in the last position of the colon operator ':'. That is not going to work.
I suggest you do this:
x = 0:0.1:1;
y = 0:0.1:1;
[X,Y] = meshgrid(x,y);
F = @(x,y) 1;
Z = F(X,Y);
Z(Y > sqrt(1-X.^2)) = 0;
And now you can use this File Exchange Contribution
I'm not sure how to use that file. Do I have this on a script and use the file as a function on another script? Sorry I'm really new to this stuff.

请先登录,再进行评论。

Try use idea by Walter (+1):
x = 0:.1:1;
f = @(x)sqrt(1 - x.^2);
[yy,xx] = ndgrid(x);
out = trapz(x,trapz(yy,f(xx)>=yy),2);

类别

帮助中心File Exchange 中查找有关 Numerical Integration and Differentiation 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by