How to create a matrix in Matlab with every entry being the output of a bivariate function

邮差的信 提交于 2019-12-11 18:23:51

问题


I want to create a 4 x 4 matrix with each entry representing f(x,y) where both x and y take values 0, 1, 2 and 3. So the first entry would be f(0,0), all the way to f(3,3).

The function f(x,y) is:

3 * cos(0*x + 0*y) + 2 * cos(0*x + 1*y) + 3 * cos(0*x + 2*y) + 8 * cos(0*x + 3*y) + 3 * cos(1*x + 0*y) + 25 * cos(1*x + 1*y) + 3 * cos(1*x + 2*y) + 8 * cos(1*x + 3*y) + 3 * cos(2*x + 0*y) + 25 * cos(2*x + 1*y) + 3 * cos(2*x + 2*y) + 8 * cos(2*x + 3*y) + 3 * cos(3*x + 0*y) + 25 * cos(3*x + 1*y) + 3 * cos(3*x + 2*y) - 90 * cos(3*x + 3*y)

I haven't used Matlab much, and it's been a while. I have tried turning f(x,y) into a @f(x,y) function; using the .* operator; meshing x and y, etc. All of it without success...


回答1:


Not sure, what you've tried exactly, but using meshgrid is the correct idea.

% Function defintion (abbreviated)
f = @(x, y) 3 * cos(0*x + 0*y) + 2 * cos(0*x + 1*y) + 3 * cos(0*x + 2*y)

% Set up x and y values.
x = 0:3
y = 0:3

% Generate grid.
[X, Y] = meshgrid(x, y);

% Rseult matrix.
res = f(X, Y)

Generated output:

f =
   @(x, y) 3 * cos (0 * x + 0 * y) + 2 * cos (0 * x + 1 * y) + 3 * cos (0 * x + 2 * y)

x =
   0   1   2   3

y =
   0   1   2   3

res =
   8.00000   8.00000   8.00000   8.00000
   2.83216   2.83216   2.83216   2.83216
   0.20678   0.20678   0.20678   0.20678
   3.90053   3.90053   3.90053   3.90053


来源:https://stackoverflow.com/questions/55841872/how-to-create-a-matrix-in-matlab-with-every-entry-being-the-output-of-a-bivariat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!