笛卡尔积的Matlab矢量化

时间:2013-03-06 19:47:29

标签: matlab vectorization

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

2 个答案:

答案 0 :(得分: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.

如果你的函数只接受标量输入,那么循环就是一个简单的选择。

答案 1 :(得分:3)

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

e.g。

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

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

M = X.^Y;