0

I am trying to numerically evaluate a double integral. The specific integral is too complicated, but it is not relevant here, I only want the main idea.

Suppose I have:

x=1;
y=1;

fun = @(theta,phi)  (x.*sin(theta) + y.*cos(phi));
result = integral2(fun,0,pi,0,2*pi)

This gives a single value. Assume I'd like to do this for a range of values for X and Y. Ideally, I'd like to have x,y as vectors:

x=1:10;
y=1:10;

Matlab gives (Error using .* Matrix dimensions must agree.)

What is the solution? (Ideally, I do not want to use for loop).

student1
  • 860
  • 3
  • 11
  • 22

1 Answers1

1

You can use arrayfun to "lift" your function when you want it to accept arrays

x = 1:10;
y = 1:10;
result = arrayfun(@(x, y) integral2(@(theta,phi) x.*sin(theta) + y.*cos(phi),0,pi,0,2*pi), x, y);

or

fun = @(theta, phi, x, y) x.*sin(theta) + y.*cos(phi);
result = arrayfun(@(x, y) integral2(@(theta,phi)fun(theta,phi,x,y), 0,pi,0,2*pi), x, y);
Dmitry Galchinsky
  • 2,181
  • 2
  • 14
  • 15
  • Thanks Dmitry, that did it! BTW, is this the "standard" way to do it? or it is a "trick" ? – student1 Mar 14 '13 at 22:58
  • It is a standard way to make a one-liner. It is not a true vectorization so it may be slow (compare `x = ones(1, 1000000);tic;x = x * 2;toc` with `y = ones(1, 1000000);tic;y = arrayfun(@(y) y*2, y);toc`) but in cases like yours (small number of iterations, heavy iterations themselves) when you can't properly vectorize it helps without any problem – Dmitry Galchinsky Mar 14 '13 at 23:09
  • I see. BTW, what if I want to use an 'alias' like z=sin(theta)*cos(phi), where z is just a shortcut to simplify the typing. I cannot define it as a variable since theta itself is not defined as proper variable. Any ideas? – student1 Mar 14 '13 at 23:55
  • You can define a function `z=@(theta, phi) sin(theta)*cos(phi)` and use it as `z(theta, phi)` – Dmitry Galchinsky Mar 14 '13 at 23:58
  • So no method will allow me to write only z? Because I am writing that tens of times and would like it to be short. – student1 Mar 15 '13 at 00:00
  • No, you'll also need to write variables to substitute in the brackets – Dmitry Galchinsky Mar 15 '13 at 00:04