2

Suppose that X, Y are the matrices of coordinates inside the given intervals

xc = 0, yc = 0
xl = linspace(xc - 10, xc + 10, 2);
yl = linspace(yc - 10, yc + 10, 2);
[X,Y] = meshgrid(xl,yl);

and fun is a handle to some function test(v)

fun = @(v)test(v);

How to combine both matrices X, Y so that they represent components x,y of the vector v

res = arrayfun(fun, [X,Y]); //First processed X and then Y

Unfortunately, this solution does not work....

There is another way when the function is modified so that two parameters x, y are passed

fun = @(x, y)test(x, y);
res = arrayfun(fun, X, Y); //This works well

However, I would like to preserve an intertace of the function if any solution exists.

Thanks for your help.

justik
  • 4,145
  • 6
  • 32
  • 53

2 Answers2

4
  • Redefine fun as fun = @(x, y)test([x,y]);

No need to modify function test()

xc = 0;
yc = 0;
xl = linspace(xc - 10, xc + 10, 2);
yl = linspace(yc - 10, yc + 10, 2);
[X,Y] = meshgrid(xl,yl);

% Given function test
test =@(v)v(1) + v(2);


% pass x, y as a vector  
fun = @(x, y)test([x,y]);


res = arrayfun(fun, X, Y);

% X =

   -10    10
   -10    10

% Y =

   -10   -10
    10    10

% fun(x, y) = x + y

% res =

   -20     0
     0    20

Adam
  • 2,726
  • 1
  • 9
  • 22
1

From Matlab doc:

B = arrayfun(func,A) applies the function func to the elements of A, one element at a time

B = arrayfun(func,A1,...,An) applies func to the elements of the arrays A1,...,An, so that B(i) = func(A1(i),...,An(i))

So you are using arrayfun in the wrong way.

Use a for loop or two nested loops instead.

for i=1:size(X,1)
    for j=1:size(X,2)
    res(i,j)=fun([X(i,j),Y(i,j)])
    end
end

What are you trying to do?

Also, in Matlab, you should use % instead of // for commenting

These are some related questions:

arrayfun when each row of the array is an input

Passing a vector as multiple inputs to a function

Amin Ya
  • 1,515
  • 1
  • 19
  • 30
  • @ Amin: I would like to avoid two nested loops for and make the code clearer. In general, this approach is significantly faster for large data than using for loops. – justik Jul 04 '19 at 07:17
  • @justik: `arrayfun` is a for loop. Why do you say it is significantly faster than a for loop? – Cris Luengo Jul 04 '19 at 13:41
  • @ Cris: You are right, there is no measurable speed increment, I tried it out. And confirmed here https://www.mathworks.com/matlabcentral/answers/324130-is-arrayfun-faster-much-more-than-for-loop – justik Jul 05 '19 at 10:23