Create a matrix from a function handle (MATLAB)

What I intend to do is simple, but I can’t find a suitable method. I have a function handle which depends on two variables, for example:

< p>

f = @(i,j) i+j

(But my situation is much more complicated)

What I want to do is create A matrix M

M(i,j) = f(i,j)

Of course I can use nested loops, but I am trying to avoid these . I have managed to do this in Maple in a very simple way:

f:=(i,j)->i+j;
M:=Matrix(N,f);

(where N is the dimension of the matrix) but I need to use MATLAB. Now I stick to nested loops, but I really appreciate your help!

Use bsxfun:

>> [ii jj] = ndgrid(1:4 ,1:5); %// change i and j limits as needed
>> M = bsxfun(f, ii, jj )

M =

2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9

If your function f meets the following conditions:

C = fun(A,B) accepts arrays A and B of arbitrary, but equal size and returns output of the same size. Each element in the output array C< /code> is the result of an operation on the corresponding elements of A and B only. fun must also support scalar expansion< /strong>, such that if A or B is a scalar, C is the result of applying the scalar to every element in the other input array.

You can handle ndg rid. Just add transpose (.') to the first (i) vector:

>> M = bsxfun(f, (1:4).' , 1:5)

What I intend to do is simple, but I can't find a suitable method. I have a function handle which depends on two variables, for example :

f = @(i,j) i+j

(But my situation is much more complicated)

What I want to do is create a matrix M

M(i,j) = f(i,j)

Of course I can use Nested loops, but I tried to avoid these. I have managed to do this in Maple in a very simple way:

f:=(i,j) ->i+j;
M:=Matrix(N,f);

(where N is the dimension of the matrix) but I need to use MATLAB. Now I insist on using nested loops, But I really appreciate your help!

Use bsxfun:

>> [ii jj ] = ndgrid(1:4 ,1:5); %// change i and j limits as needed
>> M = bsxfun(f, ii, jj)

M =< br />
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9

If your function f Meet the following conditions:

C = fun(A,B) accepts arrays A and B of arbitrary, but equal size and returns output of the same size. Each element in the output array C is the result of an operation on the corresponding elements of A and B only. fun must also support scalar expansion, such that if A< /code> or B is a scalar, C is the result of applying the scalar to every element in the other input array.

You can handle ndgrid. Just add transpose (.') to the first (i) vector:

>> M = bsxfun(f, (1:4).', 1:5)

Leave a Comment

Your email address will not be published.