Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 690
Javier Garcia Avatar asked May 26 '14 20:05

Javier Garcia


People also ask

How do you create a matrix in MATLAB?

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.

What is a function handle in MATLAB?

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).

How do you create a matrix vector in MATLAB?

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.

Can you have an array of functions in MATLAB?

The short answer is no. However, it's possible to store function handles in a cell array.


1 Answers

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)
like image 185
Luis Mendo Avatar answered Sep 28 '22 09:09

Luis Mendo