How to vectorize function with 3 input vectors and 3-dimensional matrix output?

8 views (last 30 days)
Let f = @(X,Y,Z) ...; and length(X) = Nx; length(Y) = Ny; length(Z) = Nz; How to write f if I want a matrix (M) with size Nx x Ny x Nz as an output in which M(i,j,k) = f(X(i),Y(j),Z(k)) ?

Answers (1)

Walter Roberson
Walter Roberson on 19 Dec 2017
Edited: Walter Roberson on 19 Dec 2017
[gX, gY, gZ] = ndgrid(X, Y, Z);
result = arrayfun(@f, gX, gY, gZ);
This assumes that the function f itself cannot be vectorized.
If f is receiving X, Y, Z as inputs, and the calculations it uses can be vectorized, then you can use ngrid, or you can use bsxfun(), or in R2016b and later you can use implicit expansion after having reshaped X to column vector, reshaped Y to row vector, and reshaped Z to "page vector" with reshape(Z, 1, 1, [])

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!