How to create a matrix in Matlab with every entry

2019-08-30 04:14发布

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条回答
看我几分像从前
2楼-- · 2019-08-30 04:51

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
查看更多
登录 后发表回答