Programmer
Programmer

Reputation: 133

Matlab How to iterate a function through a list

I need some help iterating over a function that depends on two variables.

So let's say I have a function that depends on two variables. Let's call it f = x + y

Now, I have a two lists, one of x variables and one of y variables. For example, xlist = [1 2 3] and ylist = [4 5 6]

And I want to go through each element of the lists and plug it into f. For example, set x=1 and then evaluate f for y=4, then y=5, then y=6... and repeat for x=2 and x=3.

Finally, I want to return a matrix of the calculated values. For the example above, the answer should be [5 6 7];[6 7 8];[7 8 9]

How would I go about doing this?

Upvotes: 0

Views: 396

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

Assuming the function can't be vectorized and thus you really need to iterate, a simple way is via ndgrid (to create x, y values that describe all possible pairs) and arrayfun (to iterate over the two x, y values at the same time):

f = @(x,y) x+y; % Or f = @fun, if fun is a function defined elsewhere
xlist = [1 2 3];
ylist = [4 5 6];
[xx, yy] = ndgrid(xlist, ylist); % all pairs
result = arrayfun(f, xx, yy);

In many cases the function can be vectorized, which results in faster code. For the example function this would be done defining f as

f = @(x,y) bsxfun(@plus, x(:), y(:).');

or in recent Matlab versions you can exploit implicit singleton expansion and just write

f = @(x,y) x(:)+y(:).';

In either case, note that the two arguments of addition are forced to be a column vector (x(:)) and a row vector (y(:).'), so that singleton expansion will automatically create all pairs:

xlist = [1 2 3];
ylist = [4 5 6];
result = f(xlist, ylist);

Upvotes: 2

kpg987
kpg987

Reputation: 486

Another way to do it would be to use two for loops:

x_values=[2,4,6,8];
y_values=[1,3,5,7];
%initialize a matrix with zeros
output_matrix=zeros(length(x_values),length(y_values));
for i=1:length(x_values)
    for j=1:length(y_values)
        output_matrix(i,j)=x_values(i)+y_values(j);
    end 
end

output_matrix

Upvotes: 1

Related Questions