Michael Sue
Michael Sue

Reputation: 105

Plot 3D figure in matlab

for example, I know how to plot this simple function in 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.

 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,

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.

Upvotes: 0

Views: 1758

Answers (1)

hbaderts
hbaderts

Reputation: 14371

This is actually specific to this implementation of the Ackley function: The function assumes, that your input looks like the following:

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

where the number of columns is the dimension (n=2, i.e. only x and y, in our case). 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

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. You can use the colon operator : to make column vectors out of X and Y, and concatenate them again:

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

Now you have the correct structure and can call 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:

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

Finally, you can plot the graph as usual:

surf(X, Y, Z);

resulting ackley function

Upvotes: 1

Related Questions