简体   繁体   English

在matlab中绘制3D图形

[英]Plot 3D figure in matlab

for example, I know how to plot this simple function in matlab例如,我知道如何在 matlab 中绘制这个简单的函数

 % simple demo
function z=myfun(x,y)
z=1./((x+y)^2+y^2+5);

This code is my way to plot the figure in matlab.这段代码是我在 matlab 中绘制图形的方式。

 x=-3:3;
y=-3:3;
[X,Y]=meshgrid(x,y);
Z=myfun(X,Y);
surf(X,Y,Z)

But if for some complex function I don't know how to do this.但是如果对于一些复杂的功能,我不知道该怎么做。 There is a function named Ackley Function,有一个名为 Ackley Function 的函数,

function [out]=ackley(in)

% dimension is # of columns of input, x1, x2, ..., xn
n=length(in(1,:));

x=in;
e=exp(1);

out = (20 + e ...
   -20*exp(-0.2*sqrt((1/n).*sum(x.^2,2))) ...
   -exp((1/n).*sum(cos(2*pi*x),2)));
return

Can someone show me how to do it?有人可以告诉我怎么做吗? Thank you.谢谢。

This is actually specific to this implementation of the Ackley function: The function assumes, that your input looks like the following:这实际上特定于 Ackley 函数的这种实现:该函数假定您的输入如下所示:

x_1    y_1    (...)
x_2    y_2    (...)
 .      .     (.
 .      .       .
 .      .        .)

where the number of columns is the dimension ( n=2 , ie only x and y , in our case).其中列数是维度( n=2 ,即在我们的例子中只有xy )。 The function acts on each row independently, so you can calculate any number of points at the same time.该函数独立作用于每一行,因此您可以同时计算任意数量的点。

When you create a meshgrid with当你创建一个meshgrid

x = -3:3;
y = -3:3;
[X,Y] = meshgrid(x,y);

you will get two matrices X and Y , but you can't directly feed them into ackley() - you have to create an input matrix as shown at the top, where each row corresponds to one point.你会得到两个矩阵XY ,但你不能直接将它们输入ackley() - 你必须创建一个输入矩阵,如顶部所示,每行对应一个点。 You can use the colon operator : to make column vectors out of X and Y , and concatenate them again:您可以使用冒号运算符:XY列向量,然后再次连接它们:

in = [X(:), Y(:)];

Now you have the correct structure and can call ackley :现在你有了正确的结构,可以调用ackley

out = ackley(in);

but the output is now a column vector, and not a matrix.但输出现在是一个列向量,而不是一个矩阵。 You will thus have to reshape it, to be a matrix:因此,您必须对其进行reshape ,使其成为一个矩阵:

Z = reshape(out, size(X));

Finally, you can plot the graph as usual:最后,您可以照常绘制图形:

surf(X, Y, Z);

结果阿克利函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM