简体   繁体   中英

Creating a matrix from a function handle (MATLAB)

What I intend to do is very simple but yet I haven't found a proper way to do it. I have a function handle which depends on two variables, for example:

f = @(i,j) i+j

(mine is quite more complicated, though)

What I'd like to do is to create a matrix M such that

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

Of course I could use a nested loop but I'm trying to avoid those. I've already managed to do this in Maple in a quite 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 for this. For now I'm sticking to the nested loops but I'd 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 satisfies the following condition:

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 or B is a scalar, C is the result of applying the scalar to every element in the other input array.

you can dispose of ndgrid . Just add a transpose ( .' ) to the first ( i ) vector:

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

Function handles can accept matrices as inputs. Simply pass a square matrix of size N where the values corresponds to the row number for i , and a square matrix of size N where the values correspond to the column number for j .

N = 5;
f = @(i,j) i+j;
M = f(meshgrid(1:N+1), meshgrid(1:N+1)')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM