how can i use integral2 for a vector-valued function ?

for example i wrote this code:
% code
f=@(x,y)x+y;
g=@(x,y)x^2+y^2;
h=@(x,y)x/y+y/x;
w=@(x,y)sin(x)+cos(y);
box=@(x,y)[f(x,y) g(x,y);h(x,y) w(x,y)];
answers=integral2(box,1,2,1,2)
i expected answers to be a 2*2 scalar matrix but i got only error... what to do?

 Accepted Answer

They’re not 'ArrayValued' in the sense integral understands, and only integral — and not integral2 — can handle array-valued arguments. Otherwise, you could just use integral twice, the second time on the result of the first.
They’re also essentially independent of each other, so integrate them individually using integral2 and then put them together in a matrix at the end.
Specifically:
% Vectorised Equations:
f = @(x,y)x+y;
g = @(x,y)x.^2+y.^2;
h = @(x,y)x./y+y./x;
w = @(x,y)sin(x)+cos(y);
intf = integral2(f,1,2,1,2);
intg = integral2(g,1,2,1,2);
inth = integral2(h,1,2,1,2);
intw = integral2(w,1,2,1,2);
answers = [intf intg; inth intw]
answers =
3.0000 4.6667
2.0794 1.0243

5 Comments

Thank you Star Strider...
But here f,g,h,w and their boundary conditions were only some simple examples.In my real code they are not only too complicated but also inseparable from their vector-valued function unless i define x,y as symbloic variables and separate them by calling function in symbolic variables( i do not want this because its too slow...). I also tested using integral twice instead of integral2 but this method was very very slow too.
my whole code depends on this integral and using reported methods cost me lots of time :(
i wonder why MATLAB does not support 'ArrayValued' option for integral2 :(
what can i do now ?
For now, it seems matlab still doesn't support this funtion. It would waste a lot of time to integrate the functions in a for loop for a lot of times.
Is there any new suggestion?
Any help is appreciated.
@祥宇 崔 — I’m not aware of any. There don’t appear to have been any changes to it in that regard since it was introduced 11 years ago. (I just now checked the documentation to be sure.)
Thanks! As you suggested, we can use 'integral' for twice only when these two variables are independent to each other. But what if we can't seperate them? For instance:
fun = @(n,x,y) sin(n*x-y).*sqrt(x-n*y);
for i=1:1e3
integral2(@(x,y) fun(i,x,y),0,2*pi,0,2*pi);
end
Is there anaway to speed it up by vectorizing it?
If you got any idea, here is my question.
Thanks!
https://ww2.mathworks.cn/matlabcentral/answers/1944314-how-to-vectorize-integral2

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!