Reputation: 578
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!
Upvotes: 6
Views: 1577
Reputation: 113
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)')
Upvotes: 0
Reputation: 112659
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 arraysA
andB
of arbitrary, but equal size and returns output of the same size. Each element in the output arrayC
is the result of an operation on the corresponding elements ofA
andB
only.fun
must also support scalar expansion, such that ifA
orB
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)
Upvotes: 3