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

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)) ?

Réponses (1)

[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, [])

Question posée :

le 19 Déc 2017

Community Treasure Hunt

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

Start Hunting!

Translated by