0

假设我有两个数组 X 和 Y,我需要一个矩阵 M(i, j) = some_func(X(i), Y(j))。我怎样才能在不使用循环的情况下得到它?

4

2 回答 2

4

最好的答案是使用 bsxfun,如果它是一个选项。根据 bsxfun 的帮助,它适用于任何一般的二元函数,只要:

  FUNC can also be a handle to any binary element-wise function not listed
    above. A binary element-wise function in the form of C = FUNC(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. FUNC 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.

如果您的函数只接受标量输入,那么循环是简单的替代方案。

于 2013-03-06T21:07:10.710 回答
3

很难回答您的模糊问题,这最终取决于您的功能。您可以做的是使用meshgrid然后执行您的操作,通常使用点运算符

例如

x = 1:5;
y = 1:3;

[X,Y] = meshgrid (x,y)

M = X.^Y;
于 2013-03-06T19:53:12.247 回答