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!
In MATLAB, you create a matrix by entering elements in each row as comma or space delimited numbers and using semicolons to mark the end of each row. In the same way, you can create a sub-matrix taking a sub-part of a matrix. In the same way, you can create a sub-matrix taking a sub-part of a matrix.
A function handle is a MATLAB® data type that stores an association to a function. Indirectly calling a function enables you to invoke the function regardless of where you call it from. Typical uses of function handles include: Passing a function to another function (often called function functions).
Conversion of a Matrix into a Row Vector. This conversion can be done using reshape() function along with the Transpose operation. This reshape() function is used to reshape the specified matrix using the given size vector.
The short answer is no. However, it's possible to store function handles in a cell array.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With