简体   繁体   中英

Plotting a 3d surface of a function

I'm learning Matlab as I am moving from software development into Artificial Intelligence. I have been learning the M language and I'm currently hitting a bit of a roadblock.

I am trying to generate a 3d surface of the Rastrigin function.

**rastm.m**
function y = rast(x)
n = 2; 
s = 0;
for j = 1:n
    s = s+(x(j)^2-10*cos(2*pi*x(j))); 
end
y = 10*n+s;

Below is the code being executed, test.m

**test.m**
syms f(x,y)
f(x,y) = s;
fsurf(f,[-5.12 5.12 -5.12 5.12]);
zlim([0 80])

When the code is executed, a 3d graph is generated of the correct proportions, but the surface is completely flat. I imagine I am misunderstanding the reference to the calculation of the Z co-ordinate called on line two of test.m

f(x,y) = s;

I'm using rast(x) incorrectly but I can't quite figure out why

Thank you

Unless you have a clear case of using symbolic maths, I suggest you avoid them and do your maths numerically, as ML/AI are numerical methods after all.

You can define the Rastrigrid function in 2D as:

[x1,x2]=meshgrid(-5.12:0.01:5.12,-5.12:0.01:5.12);
f =20+x1.^2+x2.^2-10*(cos(2*pi*x1)+cos(2*pi*x2));

or inside a function

function y = rast2D(x1,x2)
   f =20+x1.^2+x2.^2-10*(cos(2*pi*x1)+cos(2*pi*x2));
end

alternatively, if you have the Global Optimization Toolbox you can use rastriginsfcn . Its behavior seems undocumented but easy to follow:

[x1,x2]=meshgrid(-5.12:0.01:5.12,-5.12:0.01:5.12);
f=rastriginsfcn([x1(:) x2(:)]);
f=reshape(f,size(x1));

I tried to come up with a function that behaves similarly. I'd do:

function f=myRastrigrid(x)
   d=size(x,2);
   f=10*d+sum(x.^2-10*cos(2*pi*x),2);
end

Both of this cases output surf(x1,x2,f,'linestyle','none');axis tight :

在此处输入图片说明


For the curious, this is how it looks like in 3D:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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