How to vectorize function with 3 input vectors and 3-dimensional matrix output?
2 次查看(过去 30 天)
显示 更早的评论
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)) ?
0 个评论
回答(1 个)
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, [])
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!