简体   繁体   English

从函数句柄创建矩阵 (MATLAB)

[英]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 使得

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:我已经在 Maple 中以一种非常简单的方式做到了这一点:

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. (其中 N 是矩阵的维数)但我需要为此使用 MATLAB。 For now I'm sticking to the nested loops but I'd really appreciate your help!现在我坚持使用嵌套循环,但我真的很感激你的帮助!

Use bsxfun :使用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:如果您的函数f满足以下条件:

C = fun(A,B) accepts arrays A and B of arbitrary, but equal size and returns output of the same size. C = fun(A,B)接受任意大小但相等的数组AB ,并返回相同大小的输出。 Each element in the output array C is the result of an operation on the corresponding elements of A and B only.输出数组C中的每个元素都是仅对AB的相应元素进行运算的结果。 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. fun还必须支持标量扩展,这样如果AB是标量,则C是将标量应用于另一个输入数组中的每个元素的结果。

you can dispose of ndgrid .你可以处理ndgrid Just add a transpose ( .' ) to the first ( i ) vector:只需将转置 ( .' ) 添加到第一个 ( i ) 向量:

>> 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方阵,其中值对应于i的行号,以及一个大小为N方阵,其中值对应于j的列号。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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