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

답변 (1개)

Walter Roberson
Walter Roberson 2017년 12월 19일
편집: Walter Roberson 2017년 12월 19일
[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, [])

카테고리

질문:

2017년 12월 19일

편집:

2017년 12월 19일

Community Treasure Hunt

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

Start Hunting!

Translated by