Creating a matrix from a function handle (MATLAB)
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)