Evaluating 3D Function

I have a 3-D function f(x,y,z) which I want to evaluate at a discrete set of points (i.e. create an array with values of f).
My x,y,z variables are not equally spaced. What is the best way to define f?
For a 1-D function, I would normally use array operators:
x=linspace(1,5,100); f=x.^2;
For speed reasons I would like to avoid for loops.
But for higher dimensions this stops working:
x=linspace(1,5,100); y=linspace(1,5,10); f=x.^2+y.^2; <----does not work because of diff array sizes

回答 (2 件)

Sean de Wolski
Sean de Wolski 2012 年 2 月 2 日

0 投票

I would use bsxfun() to generate the grid of points in 3d. If this approach wouldn;t work, you could always use ndgrid() and actually generate the grid matrices.
Example with bsxfun:
x = [0 .3 5 100];
y = linspace(1,10,20);
z = logspace(1,2,3);
f = bsxfun(@plus,bsxfun(@plus,x',y),reshape(z,1,1,numel(z))) %just adding - nothing fancy
Benjamin Schwabe
Benjamin Schwabe 2012 年 2 月 2 日

0 投票

Hi,
another easy way to do that, is using the meshgrid command.
x = linspace(1,5,100); y=linspace(1,5,10); [X,Y] = meshgrid(x,y); F = X.^2+Y.^2;
If you want to go to even higher dimensions, you will require multidimensional arrays and for loops.
Benjamin

3 件のコメント

Sean de Wolski
Sean de Wolski 2012 年 2 月 2 日
Not true, meshgrid and ndgrid both support higher dimensions.
Walter Roberson
Walter Roberson 2012 年 2 月 2 日
Sean: http://www.mathworks.com/help/techdoc/ref/meshgrid.html
"The meshgrid function is similar to ndgrid, however meshgrid is restricted to 2-D and 3-D while ndgrid supports 1-D to N-D."
Sean de Wolski
Sean de Wolski 2012 年 2 月 2 日
Interesting, I stand corrected. I could've sworn it did the same thing as ndgrid just with x/y swapped with r/c.

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2012 年 2 月 2 日

編集済み:

2013 年 9 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by