Matlab中的曲面图 [英] surface plot in Matlab
问题描述
我正在尝试用对角矩阵绘制曲面,我正在尝试绘制的方程是f = x ^ T D x,x是2 x 1矢量,D是2 x 2矢量2个矩阵.
I am trying to graph a surface with a diagonal matrix, the equation I am trying graph is f = x^TDx, x is a 2 by 1 vector and D is a 2 by 2 matrix.
这是到目前为止的内容,但是我一直在出错.
Here is what have so far, but I keep getting error.
x = linspace(-10,10);
y = linspace(-10,10);
[X,Y] = meshgrid(x,y);
D = [1 0; 0 1];
f = @(x,y) [x,y]*D*[x,y].'; % [x,y] is 1 by 2
contour (X,Y,f(X,Y))
有人可以告诉我如何消除错误吗?谢谢
Can someone tell me how to get rid of the error? Thanks
推荐答案
由于x
和y
具有相同的长度,因此对角矩阵D
必须是大小为nxn的方阵,其中n等于2乘以x
或y
向量的长度.之所以需要将长度乘以2,是因为操作[x,y]
将水平数组串联在一起,从而复制了其中一个维度.
Since x
and y
have the same length, your diagonal matrix D
must be a square matrix of size n x n, with n equal to two times the length of your x
or y
vectors. The reason why you need to multiply the length by two is because the operation [x,y]
concatenates the arrays horizontally thus duplicating one of the dimensions.
在此示例中,D
是标识矩阵.有关更多信息,请参见 eye
.
In this example D
is the Identity matrix. See eye
for more information.
x = linspace(-10,10); % x is 1x100
y = linspace(-10,10); % y is 1x100
[X,Y] = meshgrid(x,y); % X is 100x100 and Y is 100x100
D = eye(2*numel(x)); % D is 2*100x2*100 = 200x200
f = @(x,y) [x,y]*D*[x,y].'; % [X,Y] is 100x200 and [X,Y].' is 200x100
contour (X,Y,f(X,Y))
如果您希望D
是随机对角矩阵,则可以结合 diag
和随机数生成函数之一可用,例如 randn
.
If you want D
to be a random diagonal matrix, you can accomplish this combining diag
with one of the Random Number Generation functions available, like for example randn
.
在前面的示例中,将D
替换为以下说明:
On the previous example, replace D
with the following instruction:
D = diag(randn(1,2*numel(x)));
您还可以将选择的系数提供给对角矩阵.为此,您将需要手动创建系数向量,并确保它具有足够的长度,以使其满足本文开头所述的条件.
You can also give the coefficients you choose to the diagonal matrix. To do so, you will need to create the vector of coefficients manually, making sure that it has the adequate length, so that it satisfies the conditions explained at the beginning of this post.
现在尝试按照以下说明替换D
:
Try now replacing D
with the following instructions:
v = 1:2*numel(x); % vector of coefficients: v = [1 2 ... 200]
D = diag(v);
这篇关于Matlab中的曲面图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!