Is there a two-dimensional 'map' equivalent in Matlab?
I'm trying to generate a matrix by applying a function to all combinations of elements of two vectors -- something like this:
A(i,j) = fun(X(i), Y(j));
Best solution I've found is to loop over all i and j, but I know that's ba开发者_JS百科d style in Matlab. Any suggestions?
This is basically what MESHGRID is for. It replicates vectors of values into meshes, and a function can then be applied to those meshed points. You can usually take advantage of matrix and element-wise array operations to avoid using a for loop to perform certain computations on the resulting meshes. Here's an example:
>> 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
Notice that the first input to MESHGRID (i.e. X
) is treated as running along the columns, while the second input (i.e. Y
) is treated as running down the rows. This is generally desired if X
and Y
represent Cartesian coordinates and the matrix A
is going to be plotted as a 3-D surface or mesh. However, you could also use the function NDGRID if you want this behavior "flipped". Here's the same example with 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
Notice that A
is now a 4-by-5 matrix instead of a 5-by-4 matrix.
精彩评论