matlab mashgrid 函数
meshgrid 有三种语法,用来生成三维网格矩阵或二维网格矩阵
[X,Y] = meshgrid(x,y) , x和y 都是一维数组,如x=[1:3]; y= [4:5]; 则生成的 X 和 Y 都是为 3X3 维的矩阵,
>> [X,Y] = meshgrid(1:3,4:5) X = 1 2 3 1 2 3 Y = 4 4 4 5 5 5
[X,Y] = meshgrid(x)
>> [X,Y] = meshgrid(1:3) X = 1 2 3 1 2 3 1 2 3 Y = 1 1 1 2 2 2 3 3 3
[X,Y,Z] = meshgrid(x,y,z)
>> [X,Y,Z] = meshgrid(1:3,4:5,6:8) X(:,:,1) = 1 2 3 1 2 3 X(:,:,2) = 1 2 3 1 2 3 X(:,:,3) = 1 2 3 1 2 3 Y(:,:,1) = 4 4 4 5 5 5 Y(:,:,2) = 4 4 4 5 5 5 Y(:,:,3) = 4 4 4 5 5 5 Z(:,:,1) = 6 6 6 6 6 6 Z(:,:,2) = 7 7 7 7 7 7 Z(:,:,3) = 8 8 8 8 8 8
下边用一个例子来展示如何二维网格的结果图
[X,Y] = meshgrid(-2:.2:2, -2:.2:2); Z = X .* exp(-X.^2 - Y.^2); surf(X,Y,Z)
meshgrid 和ndgrid的区别
[X,Y] = ndgrid(x,y)
>> [X,Y] = ndgrid(1:3,4:5) X = 1 1 2 2 3 3 Y = 4 5 4 5 4 5
>> [Y,X] = ndgrid(4:5,1:3) Y = 4 4 4 5 5 5 X = 1 2 3 1 2 3
从中我们可以看看出meshgrid 和 ndgrid 几乎是一样的,除了输入的X,Y的顺序要换一下 ,即 [Y,X] = ndgrid(y,x)和 [X,Y] = meshgrid(x,y)的结果是一样的。meshgrid更适合2-D或是3-D的 Cartesian space, 而ndgrid更适合多维的问题。