在Matlab中是否存在二维“地图”等价物?

时间:2011-04-22 19:28:22

标签: matlab matrix vector functional-programming

我正在尝试通过将函数应用于两个向量的所有元素组合来生成矩阵 - 如下所示:

A(i,j) = fun(X(i), Y(j));

我发现的最佳解决方案是循环遍历所有i和j,但我知道这是Matlab中的糟糕风格。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

这基本上是MESHGRID的用途。它将值向量复制到网格中,然后可以将函数应用于这些网格点。您通常可以利用matrix and element-wise array operations来避免使用for循环对生成的网格执行某些计算。这是一个例子:

>> X = 1:4;  %# A sample X vector
>> Y = 1:5;  %# A sample Y vector
>> [xMat,yMat] = meshgrid(X,Y);  %# Create 2-D meshes from the vectors X and Y
>> fun = @(x,y) x.^y;   %# A sample function, which raises each element of x to
                        %#   the corresponding element of y power
>> A = fun(xMat,yMat)   %# Apply the function to compute A

A =

           1           2           3           4
           1           4           9          16
           1           8          27          64
           1          16          81         256
           1          32         243        1024

请注意,MESHGRID的第一个输入(即X)被视为沿着列运行,而第二个输入(即Y)被视为沿着行向下运行。如果XY表示笛卡尔坐标,矩阵A将被绘制为三维曲面或网格,则通常需要这样做。但是,如果您希望“翻转”此行为,也可以使用函数NDGRID。以下是与NDGRID相同的示例:

>> [xMat,yMat] = ndgrid(X,Y);
>> A = fun(xMat,yMat)

A =

           1           1           1           1           1
           2           4           8          16          32
           3           9          27          81         243
           4          16          64         256        1024

请注意,A现在是一个4乘5矩阵,而不是5乘4矩阵。