0
votes

There are two types of problem I need to solve, we have a function of two variables f(x,y): one is x, y are vector with same length, how to evaluate function at each (x_i,y_i). In first dimension, it is simply f(x). How to achieve this in two dimension.

The other is evaluate values for each point of the mesh formed by x and y i.e., evaluate at each point (x_i,y_j) for every (i,j)

2
You need to be much more specific. What sort of functions? What have you tried so far? Have you done any research of your own? - David
For a general function with two variables - 大王花
The Matlab documentation/help centre has so many examples of this, have you read any? - David
Why can't you define a function that takes two inputs, then use element-wise operators (.*, ./, .^, etc.) on both inputs? The same applies for a grid of values. - rayryeng
Yes, that's exactly what I'm talking about. I can't really answer your question until you provide more details. - rayryeng

2 Answers

0
votes

For the first issue, can you clarify? I guess I see the first dimension case, but I don't get what you mean by 2 dimensions.

As for the mesh, it should be solved as follows. cartprod.m is my custom cartesian product function found here.

% Define Test Data
x = 1:5;
y = 2:4;

% Define Test Function
f = @(x,y) x*y;

% Permutate x/y as a grid
s = sortrows( cartprod(x,y) , 1 );

% Apply function for each permutation
a = arrayfun( f, s(:,1), s(:,2) );

% Reshape into matrix
M = reshape( a, 5, [] )   % Solution here

Please let me know if I misunderstood and please clarify the first half of the question for me!

0
votes

1.

In addition to other solutions, If you define the function with vector properties, the rest would be easy.

example:

function f = myfunc(x)
%% x is a vector or matrix including y,z,.. vectors
%
f = (1 + ((x(:,1) + x(:,2) + 1).^2);

Then easily evaluate your function as follows:

X = [1 1;2 3;1 -1];    % consider this your input data
f(X);

2.

Additionally, if you do not want to define it separately, the function can be defined also in the spot:

f = @(x)(1 + ((x(:,1) + x(:,2) + 1).^2);
f(X)