MATLAB Language Vectorization Get the value of a function of two or more arguments


In many application it is necessary to compute the function of two or more arguments.

Traditionally, we use for-loops. For example, if we need to calculate the f = exp(-x^2-y^2) (do not use this if you need fast simulations):

% code1
x = -1.2:0.2:1.4;
y = -2:0.25:3;
for nx=1:lenght(x)
   for ny=1:lenght(y)
      f(nx,ny) = exp(-x(nx)^2-y(ny)^2);

But vectorized version is more elegant and faster:

% code2
[x,y] = ndgrid(-1.2:0.2:1.4, -2:0.25:3);
f = exp(-x.^2-y.^2);

than we can visualize it:


Note1 - Grids: Usually, the matrix storage is organized row-by-row. But in the MATLAB, it is the column-by-column storage as in FORTRAN. Thus, there are two simular functions ndgrid and meshgrid in MATLAB to implement the two aforementioned models. To visualise the function in the case of meshgrid, we can use:


Note2 - Memory consumption: Let size of x or y is 1000. Thus, we need to store 1000*1000+2*1000 ~ 1e6 elements for non-vectorized code1. But we need 3*(1000*1000) = 3e6 elements in the case of vectorized code2. In the 3D case (let z has the same size asx or y), memory consumption increases dramatically: 4*(1000*1000*1000) (~32GB for doubles) in the case of the vectorized code2 vs ~1000*1000*1000 (just ~8GB) in the case of code1. Thus, we have to choose either the memory or speed.